Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

Detecting the active Link in NextJs

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.

Home Screencasts Best of Newsletter Search X