Alex Alex - 3 months ago 15
React JSX Question

React router master detail setup using nested syntax

I'm writing an app that has a master / detail type setup.

I want two different routes:


  • /items
    Item listing page (all items)

  • /items/item-slug
    Item detail page (single item)



I have the following config:

<Route name="app" component={App} path="/">
<IndexRoute component={ItemList} />
<Route name="itemList" component={ItemList} path="items">
<Route name="itemDetail" component={ItemDetail} path=":itemSlug" />
</Route>
</Route>


The listing route works but the item route is never reached (shows listing page instead of item page).

Everything works as expected with the following structure:

<Route name="app" component={App} path="/">
<IndexRoute component={ItemList} />
<Route name="itemList" component={ItemList} path="items" />
<Route name="itemDetail" component={ItemDetail} path="items/:itemSlug" />
</Route>


... but after reading react-router's documentation I was under the impression that I could use nesting to my favour.

Are there any modifications I can make to the first snippet so that the routing works as expected, or is the second snippet the correct way to address this functionality?

Answer

Assuming that you don't want to nest ItemDetail inside ItemList, you can't nest one inside the other. What I would do is something like this:

<Route name="app" component={App} path="/">
  <IndexRedirect to="items" />
  <Route path="items">
    <IndexRoute name="itemList" component={ItemList} />
    <Route name="itemDetail" component={ItemDetail} path=":itemSlug" />
  </Route>
</Route>
Comments