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 defaultLink
Supplied componentsnext/link
This will not be done automatically for us.
We can create a Link component by ourselves and store it in a fileLink.js
In 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/link
withuseRouter
Fromnext/router
.
Inside the component, we determine whether the current path name is the same ashref
The properties of the component, if it is, we attachselected
Give 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:
- Getting started with Next.js
- Next.js vs Gatsby vs create-react-app
- How to install Next.js
- Use links to link two pages in Next.js
- Dynamic content in Next.js in the router
- Use getInitialProps to feed data to Next.js components
- Use CSS to style Next.js components
- Prefetch content in Next.js
- Use a router to detect active links in Next.js
- Check the source code to confirm that SSR is working properly in Next.js
- Next.js: Fill the head tag with a custom tag
- Deploy the Next.js application now
- Next.js: Only run code on the server or client side of Next.js
- Deploy Next.js application in production
- How to analyze Next.js application bundles
- Lazy loading module in Next.js
- Add a wrapper component to your Next.js application
- Add Next.js to the icon in your application
- Next.js application bundle
- How to use Next.js router
- How to use Next.js API routing
- How to get cookies on the server side in Next.js application
- How to change the Next.js application port