12

After reading Route layouts I wanted to wrap some elements of my routes with a layout, but leave others without a layout.

Here is the example:

App.jsx

import React from 'react';
import { Routes, BrowserRouter, Route } from 'react-router-dom';

export default function App() {
  return (
    <div>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<p>Home</p>} />

          <Route element={<div style={{ background: 'red' }} />}>
            <Route path="/login" element={<p>Login</p>} />
          </Route>
        </Routes>
      </BrowserRouter>
    </div>
  );

When I go to / I can see the text "Home", it has no layout.
But when I go to /login nothing renders, it should render the red background layout wrapping the text "Login".

Here is a live code sandbox: https://stackblitz.com/edit/github-hwpla5?devtoolsheight=33&file=src/App.jsx

What I'm doing wrong?
Thanks

1 Answer 1

29

you have to render an <Outlet /> for inside your layout element to specify where the active child route should be mounted.

<Routes>
  <Route path="/" element={<p>Home</p>} />
  <Route element={<div style={{ background: 'red' }} > <Outlet /> </div>}>
    <Route path="/login" element={<p>Login</p>} />
  </Route>
</Routes>

5
  • 4
    Thank you very much, it works. The example on reactrouter.com/docs/en/v6/getting-started/… doesn't use outlet. Maybe I missunderstood.
    – Icaruk
    Dec 6, 2021 at 18:12
  • 5
    @lcaruk I don't think you misunderstood. I been struggling myself with it till finally I found this thread. Apart from the missing explicit explanation on the <Outlet />, I think the docs also misleads the readers by stating the <App /> will be rendered, while turns out it won't be. Mar 22, 2022 at 17:25
  • 2
    Same here. This part of the doc is really bad. I should give an example of "Layout" component. I am thinking about finding another library. They have lost my trust
    – Netsab612
    May 13, 2022 at 8:18
  • I find the answer link as a good complement in order to understand the role of the <Outlet /> Jul 30, 2022 at 10:07
  • How is this not in the documentation? You'd really expect that your PageLayout component needs to render children when reading the docs... Feb 23 at 10:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.