Active Link for Nested Routes
Medium · Navigation
A nav bar should highlight the section you are in. usePathname() from next/navigation returns the current path (without the query string) and re-renders the component when it changes. It only works in Client Components, so the file starts with "use client".
A simple pathname === href check is not enough: on /blog/my-first-post you are still in the Blog section.
Make the links show the active section:
- **Home** (/) is active only on exactly /. Otherwise every path would start with /.
- Other links are active on their own path and on any path below it: Blog is active on /blog and /blog/my-first-post, but **not** on /blogging-tips.
- The active link gets aria-current="page" (this tells screen readers which page is current) and className="active". Inactive links get neither.
Next: Pagination with ?page=