Author -  Sai gowtham

How to get the query params from a URL in Next.js

In this tutorial, we are going to learn about how to get the query params from a current URL in next.js.

Query Params

Query params are passed to the end of a URL by using the question mark ? followed by the key=value pairs.

Example:

localhost:3000/items?name=eraser

# key = name , value= eraser

Getting the Query Parameters

To get the query parameter from the above URL inside the <Items> component, we can use the useRouter() hook in next.js.

Items.js
import { useRouter } from "next/router";
export default function Items(props) {
  const { query } = useRouter();
  return (
    <div>
      <h1>Items page</h1>
      <p>{query.name}</p>    </div>
  );
}

In the above code, we first imported the useRouter() hook from the next/router package and invoked it inside the Items functional component then we accessed the query param data using the query object.

Multiple Query parameters

If you are passing multiple query parameters to a URL using the & (and) operator.

localhost:3000/items?name=eraser&id=11

You can access it inside the <Items> component like this.

Items.js
import {useRouter} from "next/router";

export default function Items() {
  const { query } = useRouter();
  return (
    <div>
      <h1>Items page</h1>
      <p>{query.id}</p>      <p>{query.name}</p>    </div>
  );
}

In class-based components you can access it like this:

Items.js
import React, { Component } from "react";
import { withRouter } from "next/router"

class Items extends Component {

    render() {
        const { query } = this.props.router;
        return (
            <div>
                <h1>About page</h1>
                <p>{query.id}</p>
                <p>{query.name}</p>
            </div>
        )
    }

}

export default withRouter(Items);

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY