Before we start please note that this tutorial is for NextJs 12 and prior. You can check here an updated tutorial on how to detect the active Link in NextJs 13.
One common thing we need to do is to highlight the active Link in the navigation of a NextJs app. For this example, we will begin from this basic code repository.
The initial app looks like this:
We have 2 basic pages /pages/index.js
and pages/about.js
similar to the code below:
import SiteNav from "../compoents/SiteNav"
export default () => (<div>
<SiteNav />
<h1>This is the Index page</h1>
</div>)
Both pages are using the navigation NextJs component from components/SiteNav.js
:
import Link from 'next/link'
export default ()=> {
return(
<nav style={{
lineHeight: '2rem',
backgroundColor: 'lightsalmon',
display: 'flex',
gap: '10px'
}}>
<Link href="/">
<a>Index</a>
</Link>
<Link href="/about">
<a>About</a>
</Link>
</nav>
)
}
In order to identify the active route, we will need to use the useRouter
hook. The router will provide us with a useRouter().asPath
property containing the current active path. I've renamed it below to a more intuitive name:
const { asPath: currentPath } = useRouter()
With the currentPath
property, we can now check and style the currently active link:
import Link from 'next/link'
import { useRouter } from 'next/router'
export default ()=> {
const { asPath: currentPath } = useRouter()
return(
<nav style={{
lineHeight: '2rem',
backgroundColor: 'lightsalmon',
display: 'flex',
gap: '10px'
}}>
<Link href="/">
<a style={{
border: (currentPath === '/') ? '1px dotted black' : 'none'
}}>Index</a>
</Link>
<Link href="/about">
<a style={{
border: (currentPath === '/about') ? '1px dotted black' : 'none'
}}>About</a>
</Link>
</nav>
)
}
Now, our application will have the current page highlighted in its navigation:
For a better optimization we can later move the shared imports in the _app template file.
You can see here the live deployed NextJs app to Github pages. Also the full code is here.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
thanks buddy you make life simple
Thanks Monis! Happy it was useful!