React-Router v6 confusion

Viewed 119

On ReactRouter tutorial page, they said the following

When routes have children it does two things:

  1. It nests the URLs ("/" + "expenses" and "/" + "invoices")
  2. It will nest the UI components for shared layout when the child route matches:

the "it will nest..." got me confused, what does that mean?

1 Answers

Consider the following routing example:

<Routes>
  <Route path="/" element={<Layout />}>
    <Route path="invoices" element={<Invoices />} />
    <Route path="expenses" element={<Expenses />} />
  </Route>
</Routes> 

It nests the URLs ("/" + "expenses" and "/" + "invoices")

The nested routes render their paths relative from their parent layout route.

<Routes>
  <Route path="/" element={<Layout />}>              // "/"
    <Route path="invoices" element={<Invoices />} /> // "/invoices"
    <Route path="expenses" element={<Expenses />} /> // "/expenses"
  </Route>
</Routes> 

It will nest the UI components for shared layout when the child route matches:

The Layout component at a minimum will render an Outlet component for the nested routes to be rendered into. It can also render other common UI elements, i.e. grid layouts, columns, header/content/footer, etc.

Example layout component:

import { Outlet } from 'react-router-dom';

const Layout = () => (
  <>
    <Navbar />
    <Sidebar />
    <Outlet /> // <-- nested routes components render here
    <Footer />
  </>
);

The Layout component remains mounted and only the matched routed component is changed when the URL path updates.

For more details see:

Related