How to add styling to an active link in Nextjs

Hi there,

I tried to add styling to an active link in Nextjs and I read the documentation, but it doesn´t work for my app. Can someone please let me know whats wrong with my code?

import Link from 'next/link';
import { useRouter } from 'next/router';

export default function Navigation() {
  const router = useRouter();

  return (
    <nav className="navigation">

      <Link href="/">
        <a className={router.pathname == '/' ? 'active' : ''}>HOME</a>
      </Link>

      <Link href="/link1">
        <a className={router.pathname == '/' ? 'active' : ''}>LINK1</a>
      </Link>

      <Link href="/link2">
        <a className={router.pathname == '/' ? 'active' : ''}>LINK2</a>
      </Link>
     
    </nav>
  );
}

Here are the CSS Styles:

.navigation {
  font-family: 'RobotoMono-Bold';
  display: flex;
  justify-content: center;

  background-color: var(--clr-bg-secondary);

  margin-bottom: 50px;

  a {
    color: #fff;
    padding: 10px 22px;
  }

  a:hover {
    background-color: #323952;
  }

  a:active {
    background-color: #323952;
  }
}

I would like that the background color attached to a:active will stay when the link is active. Probably something is wrong with react router??

Thanks for help! :slight_smile:

I don’t know next… but recently I use Nuxt (it’s like next but for Vue.js)… And for the active link, Nuxt add a class to that link… You could see what class does Next add to the active link and then add style to that class…

The className is “router.pathname”, but I guess thats an internal class which is connected to the :active CSS tag… ??

This article looks useful for your case, I hope it helps…

Also, I think that the router.pathname inside the className should be equal to the href in the Link tag… You are making equal to ‘/’ always…

No, the router.pathname is an object, the object that tells you in which path you are, the class (or className) is ‘active’… what that code does is verify if the actual pathname is equal to the path that you specify (in this case ‘/’). If the pathname is equal to ‘/’ then it will add the class ‘active’ if it’s not then it won’t add the class…

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.