How to add and remove query params in next js

To add a query param to a router, Firsts step is to import useRouter from next/router and access the router object returned from the hook.

import { useRouter } from "next/router";
 
const router = useRouter();

Then we can manipulate the routes as we like. More information about next/router can be found here

To append query params you can use different methods.

Method one:

   onClick={() => { //onclick is just a dummy example, it can be any function on a hook such as useEffect
            router.query.name = "xxxxxxx";
            router.push(router);
          }}


Method two:

 onClick={() => { //onclick is just a dummy example, it can be any function on a hook such as useEffect
            router.push({
              pathname: router.pathname, //gets the current path
              query: { some_query: "some_value" },
            })
          }}


To remove all the query params you can use the following method

   onClick={() => {
            //onclick is just a dummy example, it can be any function on a hook such as useEffect
            router.replace(router.pathname, {}, { shallow: true });
          }}

router.replace will prevent adding a new url entry into the history stack and shallow updates the path of the current page without rerunning getStaticProps, getServerSideProps or getInitialProps, and it defaults to false


To Remove a specific query you can use the following method.

 onClick={() => {
            //onclick is just a dummy example, it can be any function on a hook such as useEffect
            // before click : http://localhost:3000/xxx?some_query=some_value&another_query=xxxxxx
            delete router.query.some_query;
            router.push(router);
            // after click : http://localhost:3000/xxx?another_query=xxxxxx
          }}

Comments