Creating a Layout Route with Outlet
What you'll learn: How to build a persistent layout component that wraps multiple pages, keeping headers, sidebars, and footers visible across navigation.
The Core Idea
A layout route is a parent route that doesn't render a specific page itself—instead, it renders shared UI (like a header or sidebar) and uses <Outlet /> to display whichever child route is currently active. Think of it like a picture frame: the frame stays constant while the picture inside changes.
This pattern eliminates repetitive code. Instead of adding <Header /> and <Footer /> to every page component, you define them once in a layout and let child routes "fill in" the middle section.
Building a Layout Component
// AppLayout.jsx
import { Outlet } from 'react-router-dom';
function AppLayout() {
return (
<div className="app-container">
<header>
<h1>My App</h1>
<nav>{/* Navigation links */}</nav>
</header>
<main>
<Outlet /> {/* Child routes render here */}
</main>
<footer>© 2024 My Company</footer>
</div>
);
}
Configuring the Route Tree
<Routes>
<Route path="/" element={<AppLayout />}>
<Route index element={<HomePage />} />
<Route path="about" element={<AboutPage />} />
<Route path="contact" element={<ContactPage />} />
</Route>
</Routes>
When users navigate to /about, React Router renders <AppLayout /> with <AboutPage /> appearing where <Outlet /> sits. The header and footer persist—only the outlet content changes.
Why This Matters
Layout routes prevent UI flickering during navigation and make your component tree mirror your visual hierarchy. You can nest layouts infinitely: a dashboard layout inside an app layout, for example.
Key Takeaway: Layout routes with <Outlet /> create persistent UI shells that wrap multiple pages, eliminating duplicate code and maintaining consistent navigation structure across your app.