Just a few weeks until the 2021 JavaScript Full-Stack Bootcamp opens.
Signup to the waiting list!

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 Handbook

The 2021 JavaScript Full-Stack Bootcamp will start at the end of March 2021. Don't miss this opportunity, signup to the waiting list!

More next tutorials: