Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router - Nested routes not working

Tags:

My goal is to have http://mydomain/route1 render React component Component1 and http://mydomain/route2 render Component2. So, I thought it's natural to write the routes like the following:

    <Route name="route1" handler={Component1}>
        <Route name="route2" handler={Component2} />
    </Route>

    <DefaultRoute name="home" handler={Home} />
  </Route>

http://mydomain/route1 works as expected but http://mydomain/route2 renders Component1 instead.

Then I read this question and changed the routes to as follows:

    <Route name="route1" path="route1" handler={Component1} />
    <Route name="route2" path="route1/route2" handler={Component2} />

    <DefaultRoute name="home" handler={Home} />
  </Route>

Both http://mydomain/route2 and http://mydomain/route2 work as expected now. However, I don't understand why the former one does not work while it looks more logical and neater to me.

The nested syntax works for "/" and "route1" so why not "route1" and "route2"?

like image 621
ericn Avatar asked Aug 31 '15 02:08

ericn


3 Answers

The problem is that in nested routes, the router will try to mount all the components that match the hierarchy. This is best used when you want to nest components inside each other... but if you want two separate routes to match different components, they will need to be their own routes.

<Route handler={App}>   <Route path="route1" handler={Component1} />   <Route path="/route1/route2" handler={Component2} />   <DefaultRoute name="home" handler={Home} /> </Route> 

Component2 will mount (inside of App) when the URL is /route1/route2.

If you wanted to nest the components, you would need to add <RouteHandler/> to Component1 so it would render Component2 inside of it.

The reason this works is because nesting components are not the same as nesting URLs and can be handled separately by the router. Sometimes you want the components to nest but not necessarily the URLs, and vice versa.

like image 155
BradByte Avatar answered Oct 11 '22 03:10

BradByte


I was solving similar problem (Component2 was not rendered) and nested routes wasn't working because I forgot to render {this.props.children} in Component1

like image 32
Petr Odut Avatar answered Oct 11 '22 02:10

Petr Odut


When using hierarchical routes where there is navigation that needs the correct active states, a better approach is to do the following (using the syntax for RR2):

<Route path="route1">
    <IndexRoute component={Component1}/>
    <Route path="route2" component={Component2} />
 </Route>

This way when the URL is /route1/route2 any navigation links for route1 will correctly have an active state.

like image 44
Tom Avatar answered Oct 11 '22 02:10

Tom