Reputation: 717
I am using Next JS. Currently, my page is in the url
http://localhost:3000/project/613
Now, i want to push the page to
http://localhost:3000/project/613/time/123
Is there any way i can push relatively like router.push('/time/123')
Instead of entering the full URL router.push('project/613/time/123')
Upvotes: 18
Views: 17831
Reputation: 160
To update, the easiest way to do it in 2024 seems to be <Link>
and usePathName:
<Link href={`${pathname}/chapter/1`}>Chapter 1</Link>
E.g. this commit.
Upvotes: 4
Reputation: 1
I use it like this:
router.push("./time/123")
The important thing to work
{ ...
trailingSlash: true,
... }
in next.config
It works for me. Source for this solution is https://github.com/vercel/next.js/issues/44568#issuecomment-1863793248
Upvotes: -2
Reputation: 50248
While it's not exactly the same as relative routing you can prepend router.asPath
to the relative part.
router.push(`${router.asPath}/time/123`)
Meaning you don't need to explicitly set the beginning of the path.
Upvotes: 12
Reputation: 46
And for more options, if you don't want to do data fetching, you can add a shallow option. Check the docs: https://nextjs.org/docs/routing/shallow-routing
Upvotes: -4