← flaviocopes.com

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

Updated Jul 07 2021


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 (
      {menu.map((item, 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.

Wanna go from noobie to expert?

I wrote an entire book on this topic 👇

© 2023 Flavio Copes Flavio Copes using Notion to Site Notion to Site

Interested in solopreneurship?