I have been experimenting with Next.js 13, and the new /app
folder for routing. For a good user experience I wanted to highlight the active link in the navigation menu. Like so:
To make this work I extended the Next.js Link component to add specific CSS classNames to a menu item when the href attribute matches the current URL. I created a custom "NavLink" component like so.
Create a Custom NavLink Component
This is the NavLink component, by default the "active" classNames are added when the href matches the start of the URL pathname. You can use the exact
property to change it to an exact match with the whole URL pathname.
Note this code must run client side so we need to add the "use client";
directive. Also note we are importing from next/navigation
.
Use the Custom NavLink Component
Here is a quick example of how to use the custom NavLink component in a Next.js app. You basically use it as a direct replacement for the next/link
component with the one addition of the exact
parameter if you want to match to the exact url when highlighting the active menu component. Cheers!