React Router does not resolving on parameters route

Viewed 35

I'm using react-router-dom V6

<Router>
  <Routes>
    <Route path="/">
      <Route path="example" element={<h1>Example</h1>}>
        <Route path=":id" element={<p>cool</p>} />
      </Route>
    </Route>
  </Routes>
</Router>

"http://localhost:3000/example " renders Example so far good, but "https://localhost:3000/example/34" renders nothing.

What is the problem?

Please provide a why and how to solve this issue.

1 Answers

When nesting routes, the parent routes need to render an Outlet component for the nested routes to render their element content into. Route components render an Outlet by default when no element prop is provided, so this is why the "/example" route works.

Example:

import {
  BrowserRouter as Router,
  Routes,
  Route,
  Outlet,
} from 'react-router-dom';

...

<Router>
  <Routes>
    <Route path="/">
      <Route
        path="example"
        element={(
          <>
            <h1>Example</h1>
            <Outlet />
          </>
        )}
      >
        <Route path=":id" element={<p>cool</p>} />
      </Route>
    </Route>
  </Routes>
</Router>

If you don't want to render the "Example" component at the same time as its children, then render it alone on its own index route.

Example:

<Router>
  <Routes>
    <Route path="/">
      <Route path="example">
        <Route index element={<h1>Example</h1>} />
        <Route path=":id" element={<p>cool</p>} />
      </Route>
    </Route>
  </Routes>
</Router>

For more details, see:

Related