In this post, we will see how to resolve How to highlight active fragment link?
Question:I’ve a navigation bar that scrolls to the page’s sections using fragments, e.g:
I thought of something like this:
Best Answer:The current path’s fragment is only known on the client-side. This means you have to handle it on the client-side only.
You can start by creating a state variable that you’ll use to track the fragment/hash value on the client. Then use an
useEffectto set the variable value to the current path’s fragment.
useEffectis needed to set the initial value because
windowis not defined when the page gets pre-rendered on the server by Next.js. Trying to set the initial state in
useState()will either cause runtime errors on the server, or hydration mismatches on the client.
The above will handle initial page loads that contain the fragment in the URL. If you also need to handle client-side navigations that include the fragment you have to add additional logic for it.
next/router, you can listen for changes in the URL fragment during client-side transitions, then update the existing
If you have better answer, please add a comment about this, thank you!