Next.js Discord

Discord Forum

Add/Remove active class from navbar

Unanswered
Transvaal lion posted this in #help-forum
Open in Discord
Transvaal lionOP
I am trying to add and remove a class from an active link in the navbar. I was able to find a way to add a class by doing
<Link href="/">
        <a className={router.pathname == "/" ? "active" : ""}>
           Home
        </a>
      </Link>

but how do I remove an active class?

For example, if I have Home , About , Contact, FAQ as some of the navbar options, how do I remove the active class from About when I switch from Contact?

1 Reply

Use some libraries like clsx:
<Link className={clsx(pathname === "/home" || pathname.startsWith("/home/") && "active")}>
  Home
</Link>