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.

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.

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

{ title: 'Home', path: '/home' },
{ title: 'Explore', path: '/explore' },
]

const Sidebar = () => {
const router = useRouter()

return (
<div>
return (
<a
className={cursor-pointer ${ router.pathname === item.path ? 'text-blue-500' : 'hover:bg-gray-900 hover:text-blue-500' }} > {item.title} </a> </Link> ) })} </div> ) } 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
}

}



We can now use this MyLink component in the other components:

import MyLink from 'components/MyLink'

...
href={'blog'}
>
<a>Blog</a>
</MyLink>
In this case the “user” code is simpler, compared to the first technique, as you moved the logic inside MyLink.