Nested routes and layouts

Topic 2 of 3 in Routing6 min readIntermediateFree course

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:

JSX
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:

The route config has RootLayout at ‘/’, with an index Home route and a ‘courses’ route rendering CoursesLayout, whose ‘:id’ child renders Course. For the URL /courses/react, RootLayout with its header and nav renders an Outlet containing CoursesLayout, which renders a sidebar listing React, Node.js and SQL, and its own Outlet containing the Course page for React. Layouts stay mounted as you navigate.

JSX
{
  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
      ],
    },
  ],
}
JSX
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 /courses goes to /courses/react.
  • Index routes (index: true) render in the parent’s outlet when the URL matches the parent exactly — the “default tab”. Here, /courses shows PickACourse.
  • Layouts stay mounted. Moving from /courses/react to /courses/node only re-renders Course. The sidebar keeps its scroll position and state.

Passing data to children

An outlet can pass a value to whatever child renders in it:

JSX
// 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:

JSX
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:

JSX
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:

JSX
{
  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:

Text
src/
├─ routes.jsx            the createBrowserRouter config
├─ layouts/
│  ├─ RootLayout.jsx
│  └─ DashboardLayout.jsx
└─ pages/
   ├─ Home.jsx
   ├─ Courses.jsx
   └─ CoursePage.jsx

If 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.

Exercise

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.

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

// useAuth() is provided and returns { user }

export const routes = [
  // your code here
];

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: true marks 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.