How to link to nested routes in React Router

When nesting routes, be careful when you're intending to actually use relative paths to not use absolute paths. Your route definition

<Route path="/leveltwo/:idd" component={LevelTwo}/>

should instead be:

<Route path="leveltwo/:idd" component={LevelTwo}/>

The reason why <div><Link to="leveltwo/5">Go to LevelTwo</Link></div> was working is because <Link> only supports absolute paths (see above) and was actually pointing to /leveltwo/5 and the route definition you had initially was defined with an absolute path. So although the code ran, it wasn't actually running the way you had intended.


I think the problem is that you have a / in the subroute definition.

Just change this :

<Route path="/leveltwo/:idd" component={LevelTwo}/>

to

<Route path="leveltwo/:idd" component={LevelTwo}/>

The following is the working snippet

const {
  Router,
  Route,
  IndexRoute,
  Redirect,
  Link,
  IndexLink,
  hashHistory
} = ReactRouter

var App = React.createClass({
  render : function() {
  	return (
    	<div>
      	<h1>My Application</h1>
        <div><Link to="/levelone/1">Go to One</Link></div>
        <div><Link to="levelone/1/leveltwo/5">Go to Three</Link></div>
        {this.props.children}
      </div>
    )
  }
})

var Index = React.createClass({
  render : function() {
  	return (
      <div>
      	<h2>This is index route</h2>
      </div>
    )
  }
})

var LevelOne =  React.createClass({
  render : function() {
  	return (
    	<div>
      	<h2>This is LevelOne</h2>
        {this.props.children}
      </div>
    )
  }
})

var LevelTwo = React.createClass({
  render : function() {
  	return (
    	<div>
      	<h2>This is LevelTwo</h2>
      </div>
    )
  }
})


var routes= (
	<Route path= "/" component={App}>
    	<IndexRoute component={Index}/>
    	<Route path="/levelone/:id" component={LevelOne}>
            <Route path="leveltwo/:idd" component={LevelTwo}/>
        </Route>
    </Route>
)

ReactDOM.render(<Router history={ hashHistory } routes={routes}></Router>, document.getElementById('app'));
<script src="https://unpkg.com/[email protected]/dist/react-with-addons.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script>
<script src="https://npmcdn.com/[email protected]/umd/ReactRouter.js" charset="utf-8"></script>
<div id="app">
  <div>