Query Params in NEXT JS

Bawantha Rathnayaka
2 min readDec 3, 2022

In this article, I will show you how to get query parameters from a URL in Next Js.

Query parameters are a defined set of parameters attached to the end of a URL. for example, on a traveling website you might have “localhost:3000/search?location=london”. or perhaps you want to sort the places by prices. In order to sort places, you could use a price parameter like “localhost:3000/search?location-london&sort=price”

The easiest way to get query params from the URL in NEXT JS is by calling the useRouter hook.

Here is an example of how to get the location query parameter from inside of a component

Header.jsx — (pass query parameter to search page)

import React, { useState } from "react";
import { useRouter } from "next/router";

const Header = () => {
const [searchInput, setSearchInput] = useState("");
const router = useRouter();

const search = () => {
router.push({
pathname: "/search",
query: {
location: searchInput,
},
});
};

return(
<input
type="text"
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
/>
)
}
export default Header;

Search.jsx — (get location parameter and display inside the component)

import React from "react";
import { useRouter } from "next/router";

const Search = () => {
const router = useRouter();
const { location } = router.query;

return (
<>
//display query parameter
<h1> {location} </h1>
</>
)
}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Bawantha Rathnayaka
Bawantha Rathnayaka

Written by Bawantha Rathnayaka

I write about my experiences as a Software Engineer and the tech I use daily. portfolio - https://bawanthathilan.vercel.app/

No responses yet

Write a response