React: From Components to Production · Routing with React Router
Nested Routes and Layouts
Share layouts with Outlet and build dashboard-style navigation.
Nested routes render inside their parent's <Outlet />, so layouts (headers, sidebars, tabs) are shared across child pages and persist between navigations. Index routes render at the parent's path. NavLink adds an active class automatically, which suits sidebars and tabs.
import { Outlet, NavLink, createBrowserRouter } from "react-router";
function DashboardLayout() {
return (
<div className="layout">
<nav>
<NavLink to="/app" end>Overview</NavLink>
<NavLink to="/app/orders">Orders</NavLink>
<NavLink to="/app/settings">Settings</NavLink>
</nav>
<main><Outlet /></main>
</div>
);
}
const router = createBrowserRouter([
{
path: "/app",
element: <DashboardLayout />,
children: [
{ index: true, element: <Overview /> },
{ path: "orders", element: <Orders /> },
{ path: "orders/:id", element: <OrderDetail /> },
{ path: "settings", element: <Settings /> },
],
},
]);
Common pitfalls
- Forgetting
<Outlet />in the layout — child routes render nothing. - Missing
endon the overview NavLink so it's active everywhere. - Duplicating layout markup in every page.
Key points
- Children render in the parent's Outlet
- Index routes for default content
- NavLink handles active states
Further reading: React Router: nested routes
Practice questions
What does <Outlet /> do?
Answer
It marks where the matched child route renders inside a parent route's element, enabling shared layouts.
Why add end to <NavLink to="/app">?
Answer
Without it, the link counts as active for any URL starting with /app; end makes it active only on the exact path.
Open in the app to mark lessons complete, take notes and track your progress.