Categories
React Answers

How to call router.push with state in Next.js?

Spread the love

Sometimes, we want to call router.push with state in Next.js.

In this article, we’ll look at how to call router.push with state in Next.js.

How to call router.push with state in Next.js?

To call router.push with state in Next.js, we can call router.push with an object with the query property to add a query string to the destination URL.

For instance, we write

import { useRouter } from "next/router";

const Comp = () => {
  const router = useRouter();
  //...

  const go = () => {
    router.push({
      pathname: "/about",
      query: { name: "Someone" },
    });
  };
  //...
};

to call the useRouter hook to get the router.

Then we call router.push with an object with the query property set to an object to add the key-value pairs inside as query parameters appended to the pathname.

Conclusion

To call router.push with state in Next.js, we can call router.push with an object with the query property to add a query string to the destination URL.

2 replies on “How to call router.push with state in Next.js?”

You loose the type of the object properties, they all get casted to string.. Im i doing something wrong?. For instance if you call:
router.push({ pathname: /lot/${lot.id}/update, query: {company: 2, description: ”desc”, id: 50, product: [4]})
you will get in the other side: query: { company: “2”, description: “desc”, id: “50”, product: “4” } and this is really causing me a lot of pain… any suggestion?

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.