5

For what I understand now, if we pass an Outlet with context, the props after the context could be passed into child, and outlet act as a template that pass those props into any child the router may render.

My question is, what if we just set <Outlet /> without context? If it doesn't pass any props, is there any reason why we particularly want to use <Outlet /> alone?

Code may look like this

index.js

root.render(
  <BrowserRouter>
    <Routes>
      <Route path="/" element={<App />}>
        <Route path="checkout" element={<Checkout />} />
      </Route>
    </Routes>
  </BrowserRouter>
);

App.js

function App() {
  return (
    <>
      <Reset />
      <GlobalStyle />
      <Header cartItems={cartItems} />
      <Outlet />
    </>
  )
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Taiwan No.1
  • 91
  • 1
  • 1
  • 7

3 Answers3

5

The Outlet component alone allows nested routes to render their element content out and anything else the layout route is rendering, i.e. navbars, sidebars, specific layout components, etc.

<Routes>
  <Route path="/" element={<App />}>
    <Route path="checkout" element={<Checkout />} />
  </Route>
</Routes>

The Checkout component is rendered on "/checkout". The Reset, GlobalStyle, and Header components are all also rendered as part of the layout route "/" rendering App. I.E. something like the following is rendered to the DOM.

...
<Reset />
<Header cartItems={cartItems} />
<Checkout />
...
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Thanks for quick answer. Got it! So using alone still do the trick of rendering other component to Checkout but doesn't pass any props. – Taiwan No.1 Sep 01 '22 at 17:09
  • 1
    @TaiwanNo.1 The only prop the `Outlet` component has is a `context` prop that is provided out in a React context and accessible only via the [`useOutletContext`](https://reactrouter.com/en/v6.3.0/api#useoutletcontext) hook. It doesn't handle or pass around any other props to any other components if that's what you're asking about. Basically the main purpose is to allow sharing of common logic/UI in a layout route. – Drew Reese Sep 01 '22 at 17:12
  • I see! I've tried out using Outlet alone and the router still works. Thanks for answering. – Taiwan No.1 Sep 01 '22 at 17:24
2

This is the mental model I used to grasp the concept of Outlet:

Outlet

Nati Kamusher
  • 533
  • 5
  • 9
0

The element is used as a placeholder. In this case an enables the Users component to render its child routes. Thus the element will render either a or element depending on the current location.