13

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

Icaruk
  • 713
  • 2
  • 8
  • 20

1 Answers1

31

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>

Ahmed Eid
  • 4,414
  • 3
  • 28
  • 34
  • 4
    Thank you very much, it works. The example on https://reactrouter.com/docs/en/v6/getting-started/concepts#layout-routes doesn't use outlet. Maybe I missunderstood. – Icaruk Dec 06 '21 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 ``, I think the docs also misleads the readers by stating the `` will be rendered, while turns out it won't be. – Glenn Mohammad Mar 22 '22 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 '22 at 08:18
  • I find the answer [link](https://stackoverflow.com/a/69982280/9163798) as a good complement in order to understand the role of the `` – Raphael Escrig Jul 30 '22 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... – Alexander Derck Feb 23 '23 at 10:49