DEV Community

Kiran Mantha
Kiran Mantha

Posted on

How to set active class on NavLink for multiple react routes

I recently got into one use case of highlighting the navlink for multiple routes.

Lets say we have two routes

  1. customer listing (/customers).
  2. customer details (/customer-details/:customerId).

The entry point in ui is customer listing and when you click on any record, we will be navigated to customer details page.

Now i have a navlink like this

<NavLink to={PATHS.CUSTOMERS}>Customers</Navlink>
Enter fullscreen mode Exit fullscreen mode

The use case is for both the routes, the navlink should be in active state. And this is the logic i implemented:

import { NavLink, matchPath, useLocation } from "react-router-dom";

export function NavigationBar() {
  const { pathname } = useLocation();
  const setNavlinkClasses = (paths: string[]) =>
    paths.some((path) => matchPath(path, pathname))
    ? "navlink active"
    : "navlink";

  return (
    <nav>
      <NavLink
        to={PATHS.CUSTOMERS}
        className={setNavlinkClasses([PATHS.CUSTOMERS, PATHS.CUSTOMER_DETAILS])}
      >Customers</NavLink>
    </nav>
  );
}

Enter fullscreen mode Exit fullscreen mode

And that's it.

Hope it helps 😄
Kiran 👋 👋

Top comments (0)