Reputation: 2380
How can I use router.push
(or something similar) in Next.js to redirect one page to another while keeping the params and anchors?
Example:
site.com/blog/12#comments?param=somevalue¶m2=anothervalue
=> site.com/blog/some-blog-post#comments?param=somevalue¶m2=anothervalue
Is there a built-in way to do this?
Upvotes: 0
Views: 2399
Reputation: 26344
router.push
can take a partial URL object, so you can specify hash
there:
router.push({
pathname: "somewhere",
query: router.query,
hash: typeof window !== "undefined" ? window.location.hash : undefined,
});
I check if window
is defined because of Next.js SSR. If you don't have SSR you don't need this check.
Upvotes: 1