Nested Routes
Master nested routing to create complex navigation structures. This is a foundational concept in component-based UI development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world React experience. Take your time with each section and practice the examples
What are Nested Routes?
Nested routes allow you to create a hierarchy of routes where child routes are rendered within parent routes. This is useful for creating layouts and complex navigation structures.. This is an essential concept that every React developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
Basic Nested Routes
// Parent route with nested children
<Route path="/dashboard" element={<Dashboard />}>
<Route index element={<DashboardHome />} />
<Route path="profile" element={<Profile />} />
<Route path="settings" element={<Settings />} />
</Route>
// Dashboard component with Outlet
import { Outlet } from 'react-router-dom';
function Dashboard() {
return (
<div>
<nav>
<Link to="/dashboard">Home</Link>
<Link to="/dashboard/profile">Profile</Link>
<Link to="/dashboard/settings">Settings</Link>
</nav>
<main>
<Outlet />
</main>
</div>
);
}
// Child components
function DashboardHome() {
return <h1>Dashboard Home</h1>;
}
function Profile() {
return <h1>User Profile</h1>;
}
function Settings() {
return <h1>Settings</h1>;
}Complex Nested Routes
// Complex nested routing
<Route path="/admin" element={<AdminLayout />}>
<Route index element={<AdminDashboard />} />
<Route path="users" element={<UserManagement />}>
<Route index element={<UserList />} />
<Route path=":id" element={<UserDetail />} />
<Route path="new" element={<CreateUser />} />
</Route>
<Route path="products" element={<ProductManagement />}>
<Route index element={<ProductList />} />
<Route path=":id" element={<ProductDetail />} />
<Route path="new" element={<CreateProduct />} />
</Route>
</Route>
// Admin Layout Component
function AdminLayout() {
return (
<div className="admin-layout">
<header>
<h1>Admin Panel</h1>
<nav>
<Link to="/admin">Dashboard</Link>
<Link to="/admin/users">Users</Link>
<Link to="/admin/products">Products</Link>
</nav>
</header>
<main>
<Outlet />
</main>
</div>
);
}