Dan Stroot

Next.js 13 NavLink Component

This snippet shows how to create a custom NavLink component in Next.js 13 that extends the built-in Link component to add CSS classNames when the href attribute matches the current URL.

Date:


I have been experimenting with Next.js 13, and the new /app folder for routing. For a good user experience I wanted to highlight the active link in the navigation menu. Like so:

Active Menu Item

To make this work I extended the Next.js Link component to add specific CSS classNames to a menu item when the href attribute matches the current URL. I created a custom "NavLink" component like so.

1

Create a Custom NavLink Component

This is the NavLink component, by default the "active" classNames are added when the href matches the start of the URL pathname. You can use the exact property to change it to an exact match with the whole URL pathname.

Note this code must run client side so we need to add the "use client"; directive. Also note we are importing from next/navigation.

NavLink.jsx
(javascript)
'use client'
 
/*
 
NavLink: by default the active class is added when the href matches the start of the URL pathname.
Use the exact property to change it to an exact match with the whole URL pathname.
 
*/
import Link from 'next/link'
import { usePathname } from 'next/navigation'
 
export const NavLink = ({ href, exact, children, ...props }) => {
  const pathname = usePathname()
  const active = ' font-bold'
  const isActive = exact ? pathname === href : pathname.startsWith(href)
 
  if (isActive) {
    props.className += active
  }
 
  return (
    <Link href={href} {...props}>
      {children}
    </Link>
  )
}
2

Use the Custom NavLink Component

Here is a quick example of how to use the custom NavLink component in a Next.js app. You basically use it as a direct replacement for the next/link component with the one addition of the exact parameter if you want to match to the exact url when highlighting the active menu component. Cheers!

example.jsx
(javascript)
<NavLink href="/" exact className="text-grey-dark hover:text-grey-darker">
  Home
</NavLink>

References

Sharing is Caring

Edit this page