Nested routes and layouts
Overview
Most pages in an app share structure: a header and navigation on every page, a sidebar in the dashboard, tabs on a course page. With nested routes, the route configuration mirrors that structure. Each layout is written once and stays on screen as users move between the pages inside it.
Outlet
A parent route renders its layout and puts an <Outlet /> where the matching child route should appear:
import { Outlet, NavLink } from 'react-router';
function RootLayout() {
return (
<>
<header>
<NavLink to="/" end>Home</NavLink>
<NavLink to="/courses">Courses</NavLink>
</header>
<main>
<Outlet />
</main>
<footer>© Academy</footer>
</>
);
}
const router = createBrowserRouter([
{
path: '/',
Component: RootLayout,
children: [
{ index: true, Component: Home },
{ path: 'courses', Component: Courses },
{ path: 'courses/:slug', Component: CoursePage },
{ path: '*', Component: NotFound },
],
},
]);At /courses, React Router renders RootLayout, and inside its <Outlet />, Courses. The header and footer are written once.
Nesting deeper
Layouts can nest as deep as your UI does:
{
path: '/',
Component: RootLayout,
children: [
{ index: true, Component: Home },
{
path: 'courses',
Component: CoursesLayout, // sidebar with the course list
children: [
{ index: true, Component: PickACourse }, // /courses
{ path: ':id', Component: Course }, // /courses/react
],
},
],
}function CoursesLayout() {
return (
<div className="two-columns">
<aside>
{courses.map((c) => (
<NavLink key={c.id} to={c.slug}>{c.title}</NavLink>
))}
</aside>
<section>
<Outlet />
</section>
</div>
);
}Things to notice:
- Child paths are relative.
':id'under'courses'matches/courses/:id. Links inside a route can be relative too:<NavLink to={c.slug}>from/coursesgoes to/courses/react. - Index routes (
index: true) render in the parent’s outlet when the URL matches the parent exactly — the “default tab”. Here,/coursesshowsPickACourse. - Layouts stay mounted. Moving from
/courses/reactto/courses/nodeonly re-rendersCourse. The sidebar keeps its scroll position and state.
Passing data to children
An outlet can pass a value to whatever child renders in it:
// layout
<Outlet context={{ course }} />
// child
import { useOutletContext } from 'react-router';
const { course } = useOutletContext();Layout routes
A route without a path is a layout route: it wraps its children in a component without adding anything to the URL. Use it to share a layout between unrelated URLs:
children: [
{
Component: MarketingLayout, // big hero header
children: [
{ index: true, Component: Home },
{ path: 'pricing', Component: Pricing },
],
},
{
Component: AppLayout, // compact app header + sidebar
children: [
{ path: 'dashboard', Component: Dashboard },
{ path: 'courses/:slug', Component: CoursePage },
],
},
]Protecting routes
Layout routes are also a neat way to guard pages that require a login:
import { Navigate, Outlet, useLocation } from 'react-router';
function RequireAuth() {
const { user } = useAuth();
const location = useLocation();
if (!user) {
// remember where they were going, and don't leave /dashboard in history
return <Navigate to="/login" replace state={{ from: location.pathname }} />;
}
return <Outlet />;
}
const routes = [
{
path: '/',
Component: RootLayout,
children: [
{ path: 'login', Component: Login },
{
Component: RequireAuth,
children: [
{ path: 'dashboard', Component: Dashboard },
{ path: 'settings', Component: Settings },
],
},
],
},
];After logging in, the login page can send users back: navigate(location.state?.from ?? '/dashboard', { replace: true }).
In data mode, you can instead check in a loader and throw redirect('/login') before the page even renders — the next lesson shows how. Loaders avoid briefly rendering protected UI and can run in parallel with code loading.
Security reminder: route guards are about user experience. Anyone can change the JavaScript running in their browser, so your API must check authentication and permissions on every request.
Route-level code splitting
Nested routes are a natural place to split your bundle: load each page’s code only when someone visits it. In data mode, a route’s lazy property loads its module on demand:
{
path: 'admin',
lazy: async () => {
const { AdminPage } = await import('./pages/AdminPage.jsx');
return { Component: AdminPage };
},
}See Code splitting and Activity for more.
Organising route files
For larger apps, keep each page in its own file, and the route tree in one place:
src/
├─ routes.jsx the createBrowserRouter config
├─ layouts/
│ ├─ RootLayout.jsx
│ └─ DashboardLayout.jsx
└─ pages/
├─ Home.jsx
├─ Courses.jsx
└─ CoursePage.jsxIf you prefer files to define routes automatically, React Router’s framework mode and frameworks like Next.js use file-based routing, where the folder structure is the route tree.
Design tip: sketch your screens and draw boxes around the parts that stay the same as you click around. Each box is a layout route; each part that changes is an outlet.
A dashboard with nested layouts
Build routes for a learner dashboard: a root layout with a header; /dashboard (a DashboardLayout with a sidebar linking to “Overview” and “Settings”) whose index route shows Overview and whose settings child shows Settings; and /login. Protect everything under /dashboard with a RequireAuth layout route that redirects to /login (with replace) when useAuth().user is null.
import { Navigate, NavLink, Outlet } from 'react-router';
// useAuth() is provided and returns { user }
export const routes = [
// your code here
];import { Navigate, NavLink, Outlet, useLocation } from 'react-router';
function RootLayout() {
return (
<>
<header>Academy</header>
<Outlet />
</>
);
}
function RequireAuth() {
const { user } = useAuth();
const location = useLocation();
if (!user) {
return <Navigate to="/login" replace state={{ from: location.pathname }} />;
}
return <Outlet />;
}
function DashboardLayout() {
return (
<div className="dashboard">
<aside>
<NavLink to="/dashboard" end>Overview</NavLink>
<NavLink to="/dashboard/settings">Settings</NavLink>
</aside>
<main>
<Outlet />
</main>
</div>
);
}
const Overview = () => <h1>Overview</h1>;
const Settings = () => <h1>Settings</h1>;
const Login = () => <h1>Log in</h1>;
export const routes = [
{
path: '/',
Component: RootLayout,
children: [
{ path: 'login', Component: Login },
{
Component: RequireAuth, // layout route: no path
children: [
{
path: 'dashboard',
Component: DashboardLayout,
children: [
{ index: true, Component: Overview },
{ path: 'settings', Component: Settings },
],
},
],
},
],
},
];Summary
- Nested routes mirror nested UI: a parent route renders a layout, and its matching child renders inside
<Outlet />. - Child paths are relative to their parent;
index: truemarks the default child for the parent’s own URL. - Layout routes have no
path— they wrap children in UI or logic without adding a URL segment. - Layouts stay mounted while you navigate between their children, keeping their state.
- Guard private pages with a layout route (or loader) that redirects to login; the server must still check permissions.