Skip to content

Latest commit

 

History

History
76 lines (54 loc) · 2.45 KB

nextjs-navlink-component.mdx

File metadata and controls

76 lines (54 loc) · 2.45 KB
title published date summary icon tags
Next.js 13 NavLink Component
true
2022-12-23
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.
next
Javascript

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.

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.

'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>
  )
}

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!

<NavLink href="/" exact className="text-grey-dark hover:text-grey-darker">
  Home
</NavLink>

References