Skip to content

Using the router to detect the active link in Next.js

How to using the Next.js Router to detect the active link and assign a class to it, so we can style it with CSS

One very important feature when working with links is determining what is the current URL, and in particular assigning a class to the active link, so we can style it differently from the other ones.

This is especially useful in your site header, for example.

The Next.js default Link component offered in next/link does not do this automatically for us.

We can use 2 techniques. One is adding the logic to the children of Link. The other technique is to use Link inside another component which we can build to take care of this logic.

Let’s start with the first which is the simplest:

import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'

const menu = [
  { title: 'Home', path: '/home' },
  { title: 'Explore', path: '/explore' },
  { title: 'Notifications', path: '/notifications' },
]

const Sidebar = () => {
  const router = useRouter()

  return (
    <div>
      {menu.map((item, index) => {
        return (
          <Link key={index} href={item.path}>
            <a
              className={`cursor-pointer ${
                router.pathname === item.path
                  ? 'text-blue-500'
                  : 'hover:bg-gray-900 hover:text-blue-500'
              }`}
            >
              {item.title}
            </a>
          </Link>
        )
      })}
    </div>
  )
}

export default Sidebar

I’d recommend this as it’s the simplest thing you can do.

Another techinque is to create our own Link component, and we store it in a file MyLink.js in the /components folder, and import that instead of the default next/link.

Inside the component we determine if the current path name matches the href prop of the component, and if so we append the text-blue-500 class to the children.

You can use your own classes, of course. This is a Tailwind class to make the text blue.

Finally we return this children with the updated class, using React.cloneElement():

import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'

const MyLink = ({ href, children }) => {
  const router = useRouter()

  let className = children.props.className || ''
  if (router.pathname === href) {
    className = `${className} text-blue-500`
  }

  return <Link href={href}>{React.cloneElement(children, { className })}</Link>
}

export default MyLink

We can now use this MyLink component in the other components:

import MyLink from 'components/MyLink'

...
<MyLink
  href={'blog'}
>
  <a>Blog</a>
</MyLink>
<MyLink
  href={'about'}
>
  <a>About</a>
</MyLink>

In this case the “user” code is simpler, compared to the first technique, as you moved the logic inside MyLink.


→ Here's my latest YouTube video

→ Get my Next.js (pages router) Handbook

→ I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter

JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list