0

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&param2=anothervalue => site.com/blog/some-blog-post#comments?param=somevalue&param2=anothervalue

Is there a built-in way to do this?

Shahriar
  • 1,855
  • 2
  • 21
  • 45
  • See [this question](https://stackoverflow.com/questions/55182529/next-js-router-push-with-state) - you might have to push the existing state explicitly. – kelsny Nov 07 '22 at 23:48
  • I just found `router.push({ pathname: "somewhere", query: { ...router.query })`. However, I'm still looking for a way to get the anchor link. – Shahriar Nov 07 '22 at 23:52
  • What is the anchor link here? What value do you want to get/preserve? – kelsny Nov 07 '22 at 23:54
  • anchor* (hash). In the example above, I mean `#comments`. – Shahriar Nov 08 '22 at 00:02

1 Answers1

1

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.

kelsny
  • 23,009
  • 3
  • 19
  • 48
  • Note that the `window` check is not needed. `router.push` can only be called from the client-side where `window` is always defined. – juliomalves Nov 12 '22 at 18:44