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.
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.
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:
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);