Search code examples
reactjsreact-routerreact-router-dom

React Router - How to render "/:id" route within a layout route


I'm trying to render a route with "/:id" inside a Layout route as documentation shows in https://reactrouter.com/en/main/route/route#layout-routes, but it always renders <Apps> component.

Here's the layout:

<BrowserRouter>
  <ErrorBoundary>
    <Routes>
      <Route path="admin" element={<Admin />} />
      <Route element={<AdminLayout />}>
        <Route path="admin/apps" element={<Apps />} />
        <Route
          path="admin/apps/:id/artifacts"
          element={<ArtifactsAdmin />}
        />
        <Route
          path="admin/apps/:id/version"
          element={<Version />}
        />
      </Route>
    </Routes>
  </ErrorBoundary>
</BrowserRouter>

I also tried to put the two routes with ":id" inside the "/admin/apps" element but then I'm getting a warning that no route is matching.

What is the correct approach to do it?

I was expecting to render <ArtifactsAdmin> and <Version> when url changes but it always renders <Apps>.


Solution

  • The nested routes are injecting an additional "admin" path segment in the matchable paths. If you would like to match and render nested route "/admin/apps/*" then remove the additional "admin" segment.

    <BrowserRouter>
      <ErrorBoundary>
        <Routes>
          <Route path="/admin">
            <Route index element={<Admin />} />  // <-- "/admin"
            <Route path="apps" element={<AdminLayout />}>
              <Route index element={<Apps />} /> // <-- "/admin/apps"
              <Route path=":id">
                <Route
                  path="artifacts"               // <-- "/admin/apps/:id/artifacts"
                  element={<ArtifactsAdmin />}
                />
                <Route
                  path="version"                 // <-- "/admin/apps/:id/version"
                  element={<Version />}
                />
              </Route>
            </Route>
          </Route>
        </Routes>
      </ErrorBoundary>
    </BrowserRouter>
    

    Edit react-router-how-to-render-id-route-within-a-layout-route