Active links
This page explains how to implement active link detection and styling in Next.js.
Understanding active links
While the Link component enables basic navigation between routes, applications often need to highlight the current route in navigation menus to provide visual feedback to users about their location in the application.
Active link detection
To detect the active link, use the usePathname
hook from Next.js:
- Import the hook:
import { usePathname } from "next/navigation";
- Add the “use client” directive since hooks only work in client components:
"use client";
- Use the hook to get the current path:
const pathname = usePathname();
- Add logic to determine if a link is active:
const isActive = pathname === "/blog";
Here’s a complete example putting it all together:
"use client";
import Link from "next/link";import { usePathname } from "next/navigation";
export default function Navigation() { const pathname = usePathname();
const navLinks = [ { name: "Home", href: "/" }, { name: "Blog", href: "/blog" }, { name: "About", href: "/about" }, ];
return ( <nav className="flex gap-4"> {navLinks.map((link) => { const isActive = pathname === link.href;
return ( <Link key={link.name} href={link.href} className={` text-gray-600 hover:text-blue-500 transition-colors ${isActive ? "text-blue-600 font-bold" : ""} `} > {link.name} </Link> ); })} </nav> );}
Advanced path matching
When working with nested routes, you might want to consider a link active when the current path starts with the link’s href. You can modify the active detection logic in the example above:
const isActive = pathname === link.href || (pathname.startsWith(link.href) && link.href !== "/");
This approach handles nested routes like:
/blog
matches/blog/post-1
/about
matches/about/team
- Root path
/
only matches exactly
Styling active links
Apply conditional styling using CSS or Tailwind classes:
<Link href="/blog" className={` base-link-styles ${isActive ? "font-bold text-blue-600" : "text-gray-600"} `}> Blog</Link>
The active link now appears bold while inactive links display in blue, providing clear visual feedback about the current route.
Good to know
usePathname
requires the “use client” directive- Active state updates automatically on navigation