onlinecode

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

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

In this post we will give you information about How to get the query params from a URL in Next.js. Hear we will give you detail about How to get the query params from a URL in Next.jsAnd how to use it also give you demo for it if it is necessary.

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 (    &lt;div&gt;      &lt;h1&gt;Items page&lt;/h1&gt;      &lt;p&gt;{query.name}&lt;/p&gt;    &lt;/div&gt;  );}

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&amp;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 (    &lt;div&gt;      &lt;h1&gt;Items page&lt;/h1&gt;      &lt;p&gt;{query.id}&lt;/p&gt;      &lt;p&gt;{query.name}&lt;/p&gt;    &lt;/div&gt;  );}

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 (            &lt;div&gt;                &lt;h1&gt;About page&lt;/h1&gt;                &lt;p&gt;{query.id}&lt;/p&gt;                &lt;p&gt;{query.name}&lt;/p&gt;            &lt;/div&gt;        )    }}export default withRouter(Items);

Hope this code and post will helped you for implement How to get the query params from a URL in Next.js. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Exit mobile version