Ad

Hierarchical Routes With React Router

- 1 answer

If I want to have a hierarchy of routes, with active states getting applied to my navigation, but where certain levels of the navigation are purely logical.

For example if I do

<Route component={App} path="/" >
        <Route path="example" component={empty}>
            <Route path="ex1" component={ex1} />
            <Route path="ex2" component={ex2} />
            <IndexRedirect to="ex1" />
        </Route>
 </Route>

My navigation node example gets the active states correctly applied, but I then have to create an empty component, which just renders the children.

Alternatively I can flatten the routes, which means I no longer need to create an empty components but then I no longer get the active navigation states.

Is there a good solution to this? (I'm using the latest react-router v2.0.0rc5)

Ad

Answer

You can just omit the empty component. I'd write your example as:

<Route path="/" component={App} >
  <Route path="example">
    <IndexRedirect to="ex1" />
    <Route path="ex1" component={ex1} />
    <Route path="ex2" component={ex2} />
  </Route>
</Route>

This would be considered idiomatic.

Ad
source: stackoverflow.com
Ad