You can highlight the home navigation when you are on a subroute in Next.js by adding the activeClassName prop to your navigation component.
Here's an example code snippet:
import Link from 'next/link';
import { useRouter } from 'next/router';
const Navigation = () => {
const router = useRouter();
return (
<ul>
<li>
<Link href="/">
<a className={router.pathname === '/' ? 'active' : ''}>Home</a>
</Link>
</li>
<li>
<Link href="/blog">
<a className={router.pathname.startsWith('/blog') ? 'active' : ''}>Blog</a>
</Link>
</li>
</ul>
);
};
export default Navigation;
In the example above, we're using the useRouter hook to get the current pathname. We then use the ternary operator to check if the pathname matches the current route. We add the active
class name to the a
tag when the condition is true. In the case of the blog navigation, we check if the pathname starts with /blog
, as we want to highlight the navigation when we're on /blog
or any of its subroutes, such as /blog/post
.
Remember to add the active
CSS styles to your stylesheet to indicate that the navigation item is active.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-04-01 11:00:00 +0000
Seen: 11 times
Last updated: Mar 04 '23
How can I include a right-click action for the navigation menu in Angular?
What is the method of incorporating restorable push navigation with the get package in Flutter?
How to stop the navigation bar from rebuilding during navigation in Flutter's widget structure?
What is the process of personalizing the navigation title view for a MAUI ContentPage?
What is the process for using a module to include a new block in the navigation of Prestashop?