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.