Sub topic 5
Nested routes and shared layouts with Outlet
This chapter assumes you can write React function components and JSX, know the basics of useState and useEffect, and have already created a router with createBrowserRouter and RouterProvider. It also assumes you know how a route object's path and element work. Here you will learn how nested routes let several pages share one layout, how Outlet marks where child routes render, and which mistakes appear most often.
Why nest routes
Most apps repeat the same chrome on many pages: a header, a navigation bar, a sidebar. Without nesting, each page component would render that chrome itself, or you would wrap every page by hand. Both approaches repeat code and remount the shared parts on every navigation.
React Router solves this with route nesting. A route object can have a children array. The URL decides which routes match, and the matched routes render as a chain: the parent renders first, and each child renders inside its parent. The parent decides where the child appears by rendering an Outlet.
An Outlet is a component that renders the element of the next matching child route. If no child matches, it renders nothing.
A layout route
A layout route is a parent route whose main job is to render shared UI around its children. The example below has one layout and two child pages.
import { createBrowserRouter, RouterProvider, Link, Outlet } from "react-router-dom";
function Layout() {
return (
<div>
<nav>
<Link to="/">Home</Link> <Link to="/about">About</Link>
</nav>
<Outlet />
</div>
);
}
const router = createBrowserRouter([
{
path: "/",
element: <Layout />,
children: [
{ index: true, element: <h1>Home</h1> },
{ path: "about", element: <h1>About</h1> },
],
},
]);
export default function App() {
return={router} />;
}Follow what happens when the user visits /about:
- The router matches the parent route.
- It then matches the child route with path
about. Together they form the full path/about. Layoutrenders. Its<nav>appears, and<Outlet />is replaced by<h1>About</h1>.
When the user clicks the Home link, the router matches the parent and the index child. Layout stays mounted. Only the content inside the Outlet changes. Any state in Layout, such as an open menu or a text field in the sidebar, is kept.
The index: true child is an index route. It renders in the parent's Outlet when the URL matches the parent exactly. The next chapter covers index routes in more detail. For now, treat it as the default child.
How the tree maps to the screen
The route tree and the rendered component tree have the same shape. The diagram below shows the match for /about.
Matching always starts at the top of the tree. The router builds a list of matches from the outermost route to the innermost one. Each Outlet renders the next match in that list.
Relative paths in children
A child's path is relative to its parent. In the example, the child is written as "about", not "/about". The full path is the parent path joined with the child path.
You can write a child path that starts with / only if it also begins with the full parent path. This is allowed but rarely needed, and it is a common source of confusion. Prefer relative child paths.
A parent may also have no path at all. This is a pathless layout route. It adds a layout to its children without adding anything to the URL.
import { createBrowserRouter, Outlet } from "react-router-dom";
function MarketingLayout() {
return (
<section>
<header>Marketing site</header>
<Outlet />
</section>
);
}
function AppLayout() {
return (
<section>
<header>Signed-in app</header>
<Outlet />
</section>
);
}
const router = createBrowserRouter([
{
element: <MarketingLayout />,
children: [
{ path: "/", element: <h1>Welcome</h1> },
{ path: "/pricing", element: <h1>Pricing</h1> },
],
},
{
element: <AppLayout />,
children: [
{ path: "/dashboard", element: <h1>Dashboard</h1> },
{ path: "/settings", element: <h1>Settings</h1> },
],
},
]);Here / and /pricing share one layout, while /dashboard and /settings share another. The URLs stay flat. Pathless layouts are the usual way to give groups of pages different chrome without changing their URLs.
Nesting more than one level
Layouts can be nested to any depth. Each level needs its own Outlet.
import { createBrowserRouter, Link, Outlet } from "react-router-dom";
function Root() {
return (
<div>
<header>My app</header>
<Outlet />
</div>
);
}
function SettingsLayout() {
return (
<div style={{ display: "flex" }}>
<aside>
<Link to="/settings/profile">Profile</Link>
<Link to="/settings/billing">Billing</Link>
</aside>
<main>
<Outlet />
</main>
</div>
);
}
const router = createBrowserRouter([
{
path: "/",
element: <Root />,
children: [
{
path: "settings",
element: <SettingsLayout />,
children: [
{ path: "profile", element: <h2>Profile</h2> },
{ path: "billing", element: <h2>Billing</h2> },
],
},
],
},
]);For /settings/billing, three routes match: Root, SettingsLayout, and the billing route. Root's Outlet renders SettingsLayout. SettingsLayout's Outlet renders the billing heading. Switching from Profile to Billing leaves Root and SettingsLayout mounted.
Passing data to children with Outlet context
A parent can pass a value to whatever its Outlet renders. Give Outlet a context prop, and read it in the child with useOutletContext.
import { Outlet, useOutletContext } from "react-router-dom";
import { useState } from "react";
export function CounterLayout() {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount(count + 1)}>Clicked {count}</button>
<Outlet context={{ count, setCount }} />
</div>
);
}
export function CounterChild() {
const { count } = useOutletContext();
return <p>The parent count is {count}</p>;
}Use this for small amounts of data that belong to one layout. For data that depends on the URL, loaders (covered later) are usually a better fit. For data used across the whole app, use React context or a state library.
Common errors and edge cases
The table lists the problems you are most likely to meet.
| Symptom | Cause | Fix |
|---|---|---|
| The layout shows, but the child page is blank | The parent never renders `<Outlet />` | Add `<Outlet />` where the child should appear |
| A child route never matches | The child path is written with a leading `/` that does not start with the parent path | Use a relative path such as `"about"` |
| The parent URL shows only the layout | No index route exists for the parent | Add a child with `index: true` |
| `useOutletContext` returns `undefined` | The component is not rendered inside an `Outlet` that passes `context` | Pass `context` on the nearest parent `Outlet` |
| Layout state resets on navigation | The two pages are under different parent routes, so the layout remounts | Move both pages under the same layout route |
Two further points deserve attention.
- A route with
childrenand noOutlethides its children. If a parent route has noelement, React Router renders anOutletfor it automatically. If it has anelementthat omitsOutlet, the children never show. - Each
Outletrenders one level. AnOutletrenders only the next match. It does not render all descendants by itself. Deeper levels need their ownOutletin the child component.
Choosing between nesting and wrapping
You could also wrap pages in a layout component by hand, calling <Layout><Page /></Layout> inside each page. That works, but the layout remounts whenever the user moves between pages that each render their own copy. Nesting under a route keeps one layout instance alive across child navigations, and it lets the router match, load data for, and handle errors in each level separately. Later chapters rely on this: loaders and error elements attach to routes, so the route tree is where you put them.
Exercise
A router has a parent route { path: "/", element: <Layout />, children: [{ path: "reports", element: <Reports /> }] }. Visiting /reports shows the layout's header, but the Reports content is missing. Layout renders <header>Reports app</header> and nothing else. What is wrong, and what is the fix?
Show answer
Layout does not render an Outlet, so the matched child route has no place to appear. Import Outlet from react-router-dom and render <Outlet /> in Layout below the header.
Exercise
You want /login and /signup to share a centered card layout, and /dashboard to use a different layout. None of these layouts should add anything to the URL. How do you build this?
Show answer
Use two pathless layout routes, meaning routes with an element and children but no path. Put /login and /signup as children of the first, with the card layout element, and /dashboard as a child of the second. Each layout component renders an Outlet.