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 create a Link component ourselves, and we store it in a file Link.js in the Components folder, and import that instead of the default next/link.

In this component, we’ll first import React from react, Link from next/link and the useRouter hook from next/router.

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

We finally return this children with the updated class, using React.cloneElement():

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

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

  let className = children.props.className || ''
  if (router.pathname === href) {
    className = `${className} selected`
  }

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

Download my free Next.js book!

But.. wait! Don't stop here.

I created a premium training program that will transform you, quickly, into an excellent Next.js developer. Practical lessons to learn the 80% of Next.js that you need, in 20% of the time!

⬇️ ⬇️ ⬇️

Sign up to the Next.js Course now!

⬆️ ⬆️ ⬆️