If you have moved to the Next.js App Router, you probably noticed that activeClassName is gone.
To style a Sidebar link when it is active, you now have to use the usePathname hook.
The Hard Way (Manual)
You usually end up writing code like this for every single link:
'use client';
import { usePathname } from 'next/navigation';
import Link from 'next/link';
export function Navbar() {
const pathname = usePathname();
return (
<nav>
<Link
href="/"
className={pathname === '/' ? 'active' : ''}
>
Home
</Link>
{/* Repeat this logic 5 more times... */}
</nav>
);
}
This works, but it clutters your component code significantly.
The Easy Way (Using a Wrapper)
I built a tiny package to solve exactly this. It brings back the cleaner syntax we used to have.
Step 1: Install npm install next-app-active-link
Step 2: Use It works exactly like the standard Link component, but cleaner:
import { ActiveLink } from 'next-app-active-link';
<ActiveLink href="/about" activeClassName="text-blue-500 underline">
About
</ActiveLink>
That's it. It handles the usePathname logic internally, keeps your code dry, and is fully typed for TypeScript.
Npm Package Link next-app-active-link
Hope this saves you some time!
Top comments (0)