React Router DOM not rendering nested routes

Viewed 187

I have a navbar that is global i.e to be used in all pages

<BrowserRouter>
          <Routes>
            <Route path="/" element={<NavBar />}>
              <Route path="" element={<Home />} />
            </Route>
             <Route path="/about" element={<About />} />
          </Routes>
        </BrowserRouter>

It is not rendering the Home component, only the Navbar when I visit /

1 Answers

In this case NavBar is what is considered a wrapper component. For it to render any nested routes it necessarily needs to render an Outlet component.

Outlet

An <Outlet> should be used in parent route elements to render their child route elements. This allows nested UI to show up when child routes are rendered. If the parent route matched exactly, it will render a child index route or nothing if there is no index route.

Example:

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

const NavBar = () => {
  // any business logic

  return (
    <div /* any container styling, etc... */ >
      .... navbar UI ....

      <Outlet /> // <-- nested Route components rendered here

      ....
    </div>
  );
};

...

<BrowserRouter>
  <Routes>
    <Route path="/" element={<NavBar />} >
      <Route path="" element={<Home />} /> // <-- rendered into Outlet
    </Route>
    <Route path="/about" element={<About />} />
  </Routes>
</BrowserRouter>
Related