Course contentsShow
← React
Lesson 1840 of 2,39643. RoutingFree lesson

Nested Routes and Navigation State

How active link styling and navigation state work across nested route hierarchies using NavLink.

Nested Routes and Navigation State

You'll learn how to style active links intelligently within nested route hierarchies using NavLink's built-in navigation state.

The Challenge with Nested Navigation

When you have nested routes, determining which links should appear "active" becomes tricky. Should a parent link stay highlighted when viewing a child route? Should only the exact matching route show as active? NavLink provides precise control through its automatic state detection.

NavLink's Navigation State

NavLink automatically passes an object to its className or style props containing an isActive flag. In nested routes, you can control exactly what "active" means:

import { NavLink, Outlet } from 'react-router-dom';

function DashboardLayout() {
  return (
    <div>
      <nav>
        <NavLink 
          to="/dashboard"
          end  // Only active on exact match
          className={({ isActive }) => isActive ? 'active-link' : ''}
        >
          Overview
        </NavLink>
        
        <NavLink 
          to="/dashboard/settings"
          className={({ isActive }) => isActive ? 'active-link' : ''}
        >
          Settings  {/* Active for /dashboard/settings and children */}
        </NavLink>
      </nav>
      <Outlet />
    </div>
  );
}

The end Prop

Without end, a parent route link stays active when viewing children. With end, it only highlights on exact matches. This lets you style breadcrumbs differently from deep-navigation links.

Dynamic Styling

The state object also includes isPending (during navigation) and isTransitioning:

<NavLink 
  to="/dashboard/analytics"
  style={({ isActive, isPending }) => ({
    color: isActive ? 'blue' : 'black',
    opacity: isPending ? 0.5 : 1
  })}
>
  Analytics
</NavLink>

Key Takeaway: NavLink provides granular control over active styling in nested routes through its state object (isActive, isPending) and the end prop, letting you create intuitive navigation hierarchies where parent and child links respond appropriately to the current route.