Use a router to detect active links in Next.js

How to use Next.js router to detect active links and assign a class to them, so we can style them with CSS

When using links, a very important function is to determine what the current URL is, especially to assign a class to the active link, so we can set its style to be different from other URLs.

For example, this is particularly useful in the title of your website.

Next.js defaultLinkSupplied componentsnext/linkThis will not be done automatically for us.

We can create a Link component by ourselves and store it in a fileLink.jsIn the "Components" folder, then import that folder instead of the default foldernext/link.

In this component, we will first import React from itreact, Link fromnext/linkwithuseRouterFromnext/router.

Inside the component, we determine whether the current path name is the same ashrefThe properties of the component, if it is, we attachselectedGive your children lessons.

Finally, we use the updated class to return to this child byReact.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 = </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">className</span><span style="color:#e6db74">}</span><span style="color:#e6db74"> selected }

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

Download mine for freeNext.js manual


More tutorials next: