Menu
Coddy logo textTech

The Active Link

Part of the Next.js Essentials section of Coddy's React journey — lesson 34 of 47.

Every site with a navigation bar highlights the link you're currently on. To do that, a component has to know one thing the server can't tell it after the fact: which URL is on screen right now.

next/navigation hands it to you:

'use client';

import { usePathname } from 'next/navigation';

export default function Nav() {
    const pathname = usePathname();
    // on /about, pathname is the string '/about'
}

It's a hook, so the rules you already know apply: it only works in a component whose file starts with 'use client'. That's the whole reason a nav bar is usually one of the few client components in an otherwise server-rendered app: it has to re-run on every route change.

From there it's a plain comparison:

<Link
    href="/menu"
    className={pathname === '/menu' ? 'nav-link active' : 'nav-link'}
>
    Menu
</Link>

Note where the nav lives: in the layout. It renders once and survives every navigation, so pathname changing is what re-renders it, not a remount.

challenge icon

Challenge

Easy

The nav bar works, but nothing shows which page you're on. Fix that in components/Nav.jsx.

  1. Call usePathname() and store it in pathname.
  2. Give each link the className "nav-link active" when its href matches pathname, and plain "nav-link" otherwise.

The Home link points at /, the Menu link at /menu.

Try it yourself

import './globals.css';
import Nav from '../components/Nav.jsx';

export const metadata = {
    title: 'Coddy Eats',
};

export default function RootLayout({ children }) {
    return (
        <html lang="en">
            <body>
                <Nav />
                {children}
            </body>
        </html>
    );
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Next.js Essentials