history.push in nextjs
Sure! Here is an explanation of how to use history.push
in Next.js:
- Import the
useRouter
hook from thenext/router
module:
import { useRouter } from 'next/router';
- Invoke the
useRouter
hook to access the router object:
const router = useRouter();
- Use the
push
method on therouter
object to navigate to a new page:
router.push('/new-page');
The push
method accepts a string parameter that represents the URL path of the page you want to navigate to. In this example, the /new-page
path is used.
- Optionally, you can pass additional parameters to the
push
method to customize the navigation behavior. For example, you can provide apathname
to specify the URL path, aquery
object to include query parameters, and aas
value to set the displayed URL.
Here is an example that demonstrates these optional parameters:
router.push({
pathname: '/new-page',
query: { id: '123' },
as: '/custom-url'
});
In this example, the pathname
is set to /new-page
, the query
object includes a id
parameter with a value of 123
, and the as
value is set to /custom-url
.
That's it! You have now learned how to use history.push
in Next.js to navigate to a new page.