Nested routes and layouts
🏠The everyday picture
A shopping mall: the main corridor, signs and toilets are shared by every shop. Each shop fills in its own space. Nested routes share the corridor.
📘What it really is
- Routes can be nested so pages share a layout (header, menu, footer):
<Route element={<Layout />}>
<Route path="/" element={<Dashboard />} />
<Route path="/enquiries/new" element={<NewEnquiry />} />
<Route path="/enquiries/:id" element={<EnquiryDetail />} />
</Route>
- The layout shows where the child page goes with
<Outlet />:
export function Layout() {
return (
<>
<Header />
<main><Outlet /></main>
<Footer />
</>
);
}
- Layouts can nest further: a settings area with its own side menu inside the main layout.
indexroutes give a default child:<Route index element={<Dashboard />} />shows at the parent's own address.- Data shared by all pages, like the enquiries list, can be passed to
Outletwith itscontextprop and read withuseOutletContext, or kept in Context (Module 37).
🖱️Try it
Change your Layout from Module 32 to use <Outlet />, and nest all routes inside it. Check that the header and
menu stay in place while only the main area changes.
✅Quick check
What does <Outlet /> do?
Show the answer
It marks where the matched child route's page appears inside a layout.
Why use a layout route instead of adding <Header /> to every page?
Show the answer
The shared parts are written once and stay consistent; pages only contain their own content.
