1 | initial version |
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.