Part 27: Nested Routes, Layouts & Outlet Mechanics
Modern enterprise web applications frequently feature shared layouts—such as an Admin Dashboard with a persistent sidebar and top navigation bar—where only the inner content changes when moving between tabs.
1. Defining Nested Routes
In React Router v6, you nest <Route> components inside a parent <Route>:
import { Routes, Route, Outlet, Link } from 'react-router-dom';
function DashboardLayout() {
return (
<div className="flex min-h-screen">
<aside className="w-64 bg-gray-900 text-white p-4">
<h2 className="text-xl font-bold mb-6">Admin Panel</h2>
<nav className="flex flex-col gap-3">
<Link to="/dashboard">Overview</Link>
<Link to="/dashboard/users">Users</Link>
<Link to="/dashboard/settings">Settings</Link>
</nav>
</aside>
<main className="flex-1 p-6">
{/* <Outlet /> renders the matched child route component */}
<Outlet />
</main>
</div>
);
}
function Overview() { return <h3>Dashboard Overview</h3>; }
function Users() { return <h3>Manage Users</h3>; }
function Settings() { return <h3>System Settings</h3>; }
export default function App() {
return (
<Routes>
<Route path="/dashboard" element={<DashboardLayout />}>
{/* Index route renders when matching the exact parent path '/dashboard' */}
<Route index element={<Overview />} />
<Route path="users" element={<Users />} />
<Route path="settings" element={<Settings />} />
</Route>
</Routes>
);
}
2. Key Benefits of <Outlet />
- Zero Component Remounting: The sidebar and top navbar remain mounted in the DOM. Video players, audio streams, or background timers in the layout don't reset when switching sub-pages.
- Hierarchical Cleanliness: URL paths directly reflect component tree relationships.
Key Takeaways
- Use nested
<Route>tags to compose hierarchical layouts. - Place
<Outlet />inside the parent layout component where dynamic child views should render. - Use
indexroutes for the default child view.
In Part 28, we will learn Programmatic Navigation, Redirects, and 404 Catch-Alls!

