I recently got into one use case of highlighting the navlink for multiple routes.
Lets say we have two routes
- customer listing (/customers).
- 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>
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>
);
}
And that's it.
Hope it helps 😄
Kiran 👋 👋
Top comments (0)