How to Implement Outlet Component in React

This article provides a quick guide on how to implement the Outlet component from React Router in your web applications. You will learn how the Outlet component works, why it is essential for rendering nested routes, and how to set it up step-by-step with clear, practical code examples.


What is the Outlet Component?

In React Router (version 6 and above), the Outlet component is a placeholder that renders the child route elements of a parent route. It allows you to build nested layouts, such as a dashboard with a persistent sidebar and top navigation bar, where only the sub-pages change when a user navigates.

Instead of duplicating layout components on every page, you define a parent layout route once, place the <Outlet /> component where the dynamic content should appear, and let React Router handle the rest.


Step-by-Step Implementation

Follow these steps to implement the Outlet component in a React application.

Step 1: Install React Router

First, ensure you have react-router-dom installed in your React project.

npm install react-router-dom

Step 2: Create the Layout Component

Create a layout component (e.g., Layout.jsx) that will contain your shared UI elements, such as a header, navigation links, or footer. Import and place the Outlet component from react-router-dom inside this layout.

import { Outlet, Link } from "react-router-dom";

function Layout() {
  return (
    <div className="app-container">
      <header>
        <h1>My Web App</h1>
        <nav>
          <Link to="/">Home</Link> |{" "}
          <Link to="/about">About</Link> |{" "}
          <Link to="/dashboard">Dashboard</Link>
        </nav>
      </header>
      <hr />
      
      {/* The child routes will render here */}
      <main className="content">
        <Outlet />
      </main>

      <footer>
        <p>© 2024 My Web App</p>
      </footer>
    </div>
  );
}

export default Layout;

Step 3: Configure Nested Routes

Next, define your routing structure in your main configuration file (usually App.jsx or main.jsx). Set the Layout component as the parent route, and pass the specific page components as its children.

import { createBrowserRouter, RouterProvider } from "react-router-dom";
import Layout from "./Layout";
import Home from "./Home";
import About from "./About";
import Dashboard from "./Dashboard";

const router = createBrowserRouter([
  {
    path: "/",
    element: <Layout />, // Parent route containing the Outlet
    children: [
      {
        index: true, // Renders Home by default at the parent path "/"
        element: <Home />,
      },
      {
        path: "about", // Renders at "/about"
        element: <About />,
      },
      {
        path: "dashboard", // Renders at "/dashboard"
        element: <Dashboard />,
      },
    ],
  },
]);

function App() {
  return <RouterProvider router={router} />;
}

export default App;

Key Takeaways