Making an a tag active in nextjs on changing link

Viewed 2117

I have 2 pages Home page and About us page where the links for both end in /home and /about respectively. The landing page is my home page so I have set the css property for that to active so it highlights. But when I go to my about page the home page css stays active. How do I dynamically change the css when my route changes in nextJs?

My current Code:

export default function Nav({ children }) {
  return (
    <div>
      <Head>
        <title>Legacy</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
      </Head>
      <nav>
        <div className="logo">Legacy</div>
        <input type="checkbox" id="click" />
        <label for="click" className="menu-btn">
          <i className="fas fa-bars"></i>
        </label>
        <ul>
          <li>
          <Link href="http://localhost:3000/home">
            <a className="active" >
              Home
            </a>
            </Link>
          </li>
          <li>
          <Link href="http://localhost:3000/about">
            <a >About Us</a>
            </Link>
          </li>              
        </ul>
      </nav>          
    </div>
  );
}
1 Answers

Looks like you need to use the router. The router is a hook, so it updates every time the page changes.

Here's a short example:

import { useRouter } from 'next/router'

export default function Nav() {
  const router = useRouter()
  const currentRoute = router.pathname

  return (
    <Link href='/about'>
      <a className={currentRoute === '/about' ? 'active' : ''}>
        About us
      </a>
    </Link>
  )
}

I'd also recommend checking out the docs as there's much more you can do with the router:

https://nextjs.org/docs/api-reference/next/router


P.S. When creating relative links, it's best to not include the domain. So instead of http://localhost:3000/about, just use /about. It will always work, and if you ever decide to change the domain (e.g., deploying the site with Vercel), you won't need to update your code.

Related