In a previous reading, you learned how to nest routes. In those examples, the parent route did not render anything (other than the appropriate child route). But what if you want the parent route to render something in addition to the child route, such as a frame that should always be visible?
The Outlet component allows you to construct such layouts in nested routes.
By the end of this reading, you should be able to:
Outlet component to construct layouts in nested routesConsider the following nested route:
{
path: '/teams',
children: [
{
index: true,
element:
},
{
path: ':teamId',
element:
}
]
}
At first glance, the parent route /teams does not appear to render anything. However, React Router implicitly assigns an Outlet component to any route without an explicit element.
The above code is equivalent to this:
{
path: '/teams',
element: , // <-- explicit Outlet added
children: [
{
index: true,
element:
},
{
path: ':teamId',
element:
}
]
}
The Outlet component renders the child route with the best match. If no child route matches, it renders null.
By default, the router will render either the TeamsIndex component (if the path is /teams) or the TeamDetails component (if the path is /teams/:teamId). But what if you want TeamsIndex to always be visible?
You might attempt to move TeamsIndex back to the parent route like this:
// WARNING: THIS CODE WILL NOT WORK AS EXPECTED
{
path: '/teams',
element: ,
children: [
{
path: ':teamId',
element:
}
]
}
However, this will result in TeamsIndex rendering for both /teams and /teams/:teamId, preventing TeamDetails from displaying.
To ensure both TeamsIndex and TeamDetails render correctly, you should include an Outlet in the parent route:
{
path: '/teams',
element:
<>
>,
children: [
{
path: ':teamId',
element:
}
]
}
Now, React Router will correctly render:
TeamsIndex at /teamsTeamsIndex and TeamDetails at /teams/:teamIdFor more fine-grained control, you can also include the Outlet component inside the TeamsIndex component itself.
In this reading, you learned how to use the Outlet component to:
To deepen your understanding, explore these topics:
The Outlet component is a powerful feature of React Router, allowing for better structured and more dynamic route rendering in React applications.