Active Links in NextJS

How to highlight the active links in navbar depending on the current page.


The problem is that the user is on some page and that page happens to part of the one of the navbar links. For example, user is on about page of a website. And that about page anchor link is also available in the nav-links provided in the navigation panel at the top. And you want to highlight that about link. How to accompilish it in Next-JS?

If we break down the idea, then the implementation become really simple. The concept is that on page load, one needs to know what is the current page as indicated via url. Once you get the page, just match it from one of the links and vola, you get your culprit. To get the current page, the parameter that is useful in this context is 'usePathname()' hook. This can be utlised as shown below:

NavMenu.tsx
"use client";
 
import React from "react";
import Link from "next/link";
import { headerLinks } from "@/constants";
import { usePathname } from "next/navigation";
 
const NavMenu = () => {
  const pathName = usePathname();
 
  return (
    <ul className="flex md:flex-between w-full flex-col md:flex-row items-start gap-5">
      {headerLinks.map((item) => {
        const isActive = pathName === item.route;
 
        return (
          <li
            key={item.label}
            className={`${
              isActive && "text-primary-500"
            } flex-center p-medium-16 whitespace-nowrap`}
          >
            <Link href={item.route}>{item.label}</Link>
          </li>
        );
      })}
    </ul>
  );
};

The catch is that the current page may be nested multiple levels below. In that case, usePathname would provide the breakable path which can be handled via js.

To use this hook, the component must be client side and would require 'use-client' directive. Also, this implementation is for App-router

[1] https://nextjs.org/docs/app/api-reference/functions/use-pathname