Resolved: How to highlight active fragment link?

In this post, we will see how to resolve How to highlight active fragment link?


I’ve a navigation bar that scrolls to the page’s sections using fragments, e.g:
How do I apply a style to the navigation link while active (user is in http://myurl/#section_dev)?
I thought of something like this:
But the problem is that this functionality appears to be server side, so the router doesn’t know the current fragment.

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 useEffect to set the variable value to the current path’s fragment.
The useEffect is needed to set the initial value because window is 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.
Using next/router, you can listen for changes in the URL fragment during client-side transitions, then update the existing routeHash variable.
Here’s a codesandbox link showcasing the above solution:

If you have better answer, please add a comment about this, thank you!