Shahriar
Shahriar

Reputation: 2380

router.push with parameters in Next.js

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?

Upvotes: 0

Views: 2399

Answers (1)

tenshi
tenshi

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

Related Questions