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:
- Getting started with Next.js
- Next.js vs Gatsby vs create-react-app
- How to install Next.js
- Linking two pages in Next.js using Link
- Dynamic content in Next.js with the router
- Feed data to a Next.js component using getInitialProps
- Styling Next.js components using CSS
- Prefetching content in Next.js
- Using the router to detect the active link in Next.js
- View source to confirm SSR is working in Next.js
- Next.js: populate the head tag with custom tags
- Deploying a Next.js application on Now
- Next.js: run code only on the server side or client side in Next.js
- Deploying a Next.js app in production
- How to analyze the Next.js app bundles
- Lazy loading modules in Next.js
- Adding a wrapper component to your Next.js app
- The icons added by Next.js to your app
- The Next.js App Bundles
- How to use the Next.js Router
- How to use Next.js API Routes
- How to get cookies server-side in a Next.js app
- How to change a Next.js app port