Ask Your Question
1

How can I highlight the home navigation when I am on a subroute, such as blog/post, in Next.js?

asked 2022-04-01 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-03-04 12:00:00 +0000

qstack gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2022-04-01 11:00:00 +0000

Seen: 11 times

Last updated: Mar 04 '23