Brandon Brandon - 4 months ago 8
React JSX Question

Can't get nested route to match using React Router

I'm having trouble getting a nested route to match:

<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="about" component={About} />
<Route path="work" component={Work}>
<Route path=":slug" component={Sample} />
</Route>
</Route>
</Router>


Given this router, I can't match a route such as:
/work/sample-1
The app doesn't throw an error, nor can I log any statements on the
Sample
class.

Even if I hard-code the value I'm attempting to match, it won't work. If I un-nest the route, and set the path to
work/:slug
it will work as expected.

What am I doing wrong?

Answer

Finally found the pattern I was looking for in the "sidebar" example on the React Router Github Page

I nested the route:

<Router history={browserHistory}>
  <Route path="/" component={App}>
    <Route path="work" component={Work}>
      <Route path=":slug" component={Sample} />
    </Route>
  </Route>
</Router>

Then in the render method of the Work component, I simply needed to display the children of the route, or the remainder of the component:

render() {
    <div>
        {this.props.children ||
        <div>
            {/* rest of "Work" component here */}
        </div>}
    </div>
}

Now, when I navigate to the nested route, my navigational item is selected, and the nested content is displayed.