flppv
flppv

Reputation: 4289

Nested route under id

Is there a way to nest a route using react-router v6 this way?

<Parent>
  <Routes>
    <Route path="/items/:itemId" element={<ItemPage />} />
  </Routes>
</Parent>
<ItemPage>
  <Routes>
    <Route path="info" element={<ItemInfo />} />
    <Route path="settings" element={<ItemSettings />} />
  </Routes>

  <Sidebar />
</ItemPage>

So I could visit /items/123/settings? I am looking for indeed this way to work with router, so on separate ItemPage component layout would depend on child-route, keeping Sidebar on the side, but changing content according to info/settings "tab" selected. Everywhere else in my app this way works, but for some reason it doesn't work with nested routes under :id.

This doc does show an example for kinda nested route, but it's not a nested one.

Upvotes: 1

Views: 1311

Answers (1)

Drew Reese
Drew Reese

Reputation: 202846

Yes, the routes in the parent Routes component need to append the * wildcard matcher to the route so nested routes can also be matched. Nested Routes components build relative routes.

See How do I nest routes deep in the tree?

Example:

<Parent>
  <Routes>
    <Route path="/items/:itemId/*" element={<ItemPage />} />
  </Routes>
</Parent>

...

<ItemPage>
  <Routes>
    <Route path="info" element={<ItemInfo />} />         // "/items/:itemId/info"
    <Route path="settings" element={<ItemSettings />} /> // "/items/:itemId/settings"
  </Routes>

  <Sidebar />
</ItemPage>

Upvotes: 2

Related Questions