How to target active link when the route is active in Next.js?

Sometimes, we want to target active link when the route is active in Next.js.

In this article, we’ll look at how to target active link when the route is active in Next.js.

How to target active link when the route is active in Next.js?

To target active link when the route is active in Next.js, we can set the className prop to return the class name we want after we check the current route we’re on.

For instance, we write

import Link from "next/link";
import { useRouter } from "next/router";

export const Nav = () => {
  const router = useRouter();

  return (
    <ul>
      <li className={router.pathname === "/" ? "active" : ""}>
        <Link href="/">home</Link>
      </li>
      <li className={router.pathname === "/about" ? "active" : ""}>
        <Link href="/about">about</Link>
      </li>
    </ul>
  );
};

to add the Nav component that calls the useRouter hook to return the router object.

And then we use the router.pathname property to check the current route we’re on.

We then set className to 'active' if router.pathname returns the route value we’re checking again and an empty string otherwise.

Conclusion

To target active link when the route is active in Next.js, we can set the className prop to return the class name we want after we check the current route we’re on.