Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 70

Nested Layouts with Nested Routes and Outlets

Recommended resources

Hello! Welcome to another lesson in our module on client-side routing.

In the last lesson, you learned how to use the useNavigate hook to perform programmatic navigation. This gave you the power to redirect users based on application logic, such as after a form submission. Now, we're going to shift our focus from how we navigate to what the user sees as they move between related pages.

This lesson addresses the learning outcome: Create nested UI layouts using nested routes and the <Outlet> component. We'll explore a powerful React Router pattern that allows you to create persistent UI elements, like sidebars or headers, that are shared across multiple routes. This is fundamental for building complex, real-world applications like dashboards, admin panels, and multi-step forms.

The Problem: Repetitive Layouts

Imagine you're building a user dashboard with several sections: Profile, Analytics, and Settings. The URLs might look like this:

  • /dashboard/profile
  • /dashboard/analytics
  • /dashboard/settings

A common requirement is for all these pages to share a common layout, such as a sidebar for navigation and a consistent header. Without a smart routing strategy, you might find yourself implementing each page component separately and including the sidebar in each one:

// ProfilePage.tsx
function ProfilePage() {
  return (
    <div>
      <DashboardSidebar />
      <main>
        <h1>My Profile</h1>
        {/* ...profile content... */}
      </main>
    </div>
  );
}

// AnalyticsPage.tsx
function AnalyticsPage() {
  return (
    <div>
      <DashboardSidebar />
      <main>
        <h1>Analytics</h1>
        {/* ...analytics content... */}
      </main>
    </div>
  );
}

This approach violates the "Don't Repeat Yourself" (DRY) principle. If you need to update the sidebar, you have to do it in multiple files. React Router provides a much more elegant solution: nested routes.


The Solution: Nested Routes and the <Outlet>

The core idea is to create a hierarchical relationship between your routes. You define a parent route that renders a shared layout component. This layout component then specifies where its child routes should be rendered.

Let's break this down into two key parts:

  1. Nesting Routes: You can nest <Route> elements inside one another in your router configuration. The parent route establishes a base path and a layout, and the child routes build upon that path.
  2. The <Outlet> Component: This is a special component provided by React Router that you place inside your parent layout component. It acts as a placeholder, and React Router will automatically render the matched child route's element in its place.

This image provides a great visual explanation. The sidebar and header are part of a parent layout, and the content in the "outlet" area changes as you navigate between child routes.

React Router Nested Routes and Outlet Component Illustration
A visual demonstration of a persistent dashboard layout. The sidebar remains constant while the main content area, marked by the `<Outlet>`, dynamically renders the content for the profile, posts, or friends route.

To see this in action, let's watch a video that demonstrates how to configure nested routes and use the <Outlet> component.

Learn React Router v6 In 45 Minutes

This video from Web Dev Simplified clearly explains the concept of nesting routes to create shared layouts. It shows how to refactor a flat list of routes into a nested structure and introduces the <Outlet> component as the mechanism for rendering the child content.

Watch from 16:42 to 21:51. Pay close attention to how the routes starting with /books are grouped under a single parent <Route>, and how the BookLayout component uses <Outlet> to render the specific book page.


Implementing a Nested Layout

Let's solidify this understanding by building a simple dashboard example.

Step 1: Configure Nested Routes

First, we'll update our router configuration (likely in main.tsx) to define the nested structure. We'll have a parent route for /dashboard that renders a DashboardLayout component, and child routes for the different sections.

Notice the index route. This special route renders in the <Outlet> when the user navigates to the parent's exact path (/dashboard).

// In your router configuration file (e.g., main.tsx)

import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import DashboardLayout from './layouts/DashboardLayout';
import DashboardIndex from './pages/DashboardIndex';
import UserProfile from './pages/UserProfile';
import UserSettings from './pages/UserSettings';

const router = createBrowserRouter([
  // ... other routes like Home, About, etc.
  {
    path: '/dashboard',
    element: <DashboardLayout />,
    children: [
      {
        index: true, // Renders at /dashboard
        element: <DashboardIndex />,
      },
      {
        path: 'profile', // Renders at /dashboard/profile
        element: <UserProfile />,
      },
      {
        path: 'settings', // Renders at /dashboard/settings
        element: <UserSettings />,
      },
    ],
  },
]);

Step 2: Create the Layout Component

Next, we create the DashboardLayout component. This component contains the shared UI (our sidebar) and, crucially, the <Outlet> component to render the children.

// src/layouts/DashboardLayout.tsx

import React from 'react';
import { NavLink, Outlet } from 'react-router-dom';

export default function DashboardLayout() {
  const activeStyle = {
    fontWeight: 'bold',
    color: 'red',
  };

  return (
    <div style={{ display: 'flex', height: '100vh' }}>
      <aside style={{ width: '200px', borderRight: '1px solid #ccc', padding: '1rem' }}>
        <h2>Dashboard</h2>
        <nav>
          <ul style={{ listStyle: 'none', padding: 0 }}>
            <li style={{ margin: '1rem 0' }}>
              <NavLink 
                to="/dashboard" 
                end // 'end' prop ensures this only matches the exact path
                style={({ isActive }) => isActive ? activeStyle : undefined}
              >
                Welcome
              </NavLink>
            </li>
            <li style={{ margin: '1rem 0' }}>
              <NavLink 
                to="/dashboard/profile"
                style={({ isActive }) => isActive ? activeStyle : undefined}
              >
                Profile
              </NavLink>
            </li>
            <li style={{ margin: '1rem 0' }}>
              <NavLink 
                to="/dashboard/settings"
                style={({ isActive }) => isActive ? activeStyle : undefined}
              >
                Settings
              </NavLink>
            </li>
          </ul>
        </nav>
      </aside>

      <main style={{ flex: 1, padding: '1rem' }}>
        {/* Child route components will be rendered here */}
        <Outlet />
      </main>
    </div>
  );
}

Note: The end prop on the first <NavLink> is important. Without it, /dashboard would be considered "active" for all child routes (like /dashboard/profile), since their paths start with /dashboard.

Step 3: Create the Child Page Components

Finally, we create the simple components for each page. These contain only the content specific to that page.

// src/pages/DashboardIndex.tsx
export default function DashboardIndex() {
  return <h3>Welcome to your dashboard!</h3>;
}

// src/pages/UserProfile.tsx
export default function UserProfile() {
  return <h3>User Profile Page</h3>;
}

// src/pages/UserSettings.tsx
export default function UserSettings() {
  return <h3>User Settings Page</h3>;
}

Now, when you navigate between /dashboard, /dashboard/profile, and /dashboard/settings, the DashboardLayout remains on the screen, and only the content inside the <main> tag (where <Outlet /> is) will change.

Test your understanding!

You want to add a new page, "Notifications," to the dashboard at the path /dashboard/notifications. What are the two essential changes you need to make to your codebase to implement this?

Show answer
  1. Update the router configuration: You need to add a new route object to the children array of the /dashboard route.
    // ... inside the children array
    {
      path: 'notifications',
      element: <NotificationsPage />,
    }
    
  2. Create the component: You need to create the new NotificationsPage.tsx component that will be rendered. You would also likely add a <NavLink to="/dashboard/notifications">Notifications</NavLink> to your DashboardLayout component so users can navigate to it.

For a more in-depth text-based explanation and a complete example you can review, I recommend reading the following article. It compares the modern <Outlet> pattern to an older way of doing nested routing, which can provide useful context.

The Guide to Nested Routes with React Router

Please read this guide from ui.dev. It provides a clear, written explanation of nested routes and refactors an application from an older pattern to the modern <Outlet> approach.

First, read the section starting with 'You declaratively nest the child Route...' to understand the core concept of <Outlet>. Then, jump to the section that begins with 'Now, let's throw all that out the window and refactor our app using the Outlet component.' This will show you a practical example of how clean and declarative the <Outlet> pattern is.


Advanced: Passing Data to Child Routes with useOutletContext

A common scenario is that the parent layout component might fetch data that all child routes need (e.g., fetching the current user's data in DashboardLayout). How do you pass this data down into the component being rendered by <Outlet>?

You can't pass props to <Outlet> directly. Instead, React Router provides a built-in mechanism: the context prop on <Outlet> and the useOutletContext hook.

The parent layout can pass a value to the context prop:

// DashboardLayout.tsx
const [user, setUser] = useState({ name: 'Alex' });
// ...
<Outlet context={{ user }} />

And any child component rendered by that outlet can access it with the useOutletContext hook:

// UserProfile.tsx
import { useOutletContext } from 'react-router-dom';

type DashboardContext = {
  user: { name: string } | null;
};

export default function UserProfile() {
  const { user } = useOutletContext<DashboardContext>();

  return <h3>Profile for {user?.name}</h3>;
}

This is a clean, built-in alternative to creating a full React Context for data that only needs to flow from a parent layout to its immediate children.

The official documentation provides an excellent TypeScript example, which establishes a best practice of creating a custom hook to consume the context. This improves type safety and reusability.

useOutletContext

Please read the official React Router documentation for useOutletContext. Focus on the 'more realistic example' with TypeScript.

Read the section titled 'Here's a more realistic example:'. Notice how they define a ContextType, pass a value to <Outlet context={...} />, and then export a custom useUser hook. This is a production-grade pattern you will find very useful.


Conclusion

Today you've learned one of the most important patterns for building scalable and maintainable user interfaces with React Router. By creating shared layouts with nested routes and the <Outlet> component, you can keep your UI consistent and your code DRY.

Key Takeaways:

  • Nested routes allow you to create hierarchical URL structures and UI layouts.
  • A parent route component acts as a layout, containing shared UI like sidebars or headers.
  • The <Outlet /> component is a placeholder within the layout where child route elements are rendered.
  • An index route specifies the default component to render at the parent's base path.
  • You can pass data from a parent layout to its child routes using the context prop on <Outlet> and the useOutletContext hook.

Preview of the Next Lesson:
Now that we can group routes into a shared layout (like a protected dashboard), the next logical step is to control who can access them. In the next lesson, we will implement protected routes to restrict access based on authentication status, combining what you've learned about layouts, programmatic navigation, and state to build secure areas of your application.