Skip to content

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

The Valley of Code

Your Web Development Manual

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 (
      {, index) => {
        return (
          <Link key={index} href={item.path}>
              className={`cursor-pointer ${
                router.pathname === item.path
                  ? 'text-blue-500'
                  : 'hover:bg-gray-900 hover:text-blue-500'

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'


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

  • THE VALLEY OF CODE (+ PRO), your web development manual
  • I wrote 15+ free coding BOOKS, download them here
  • SOLOPRENEUR LAND the missing MBA for wannabe solopreneurs craving a life with more freedom, control, fulfillment and purpose (summer 2024)