简体   繁体   中英

Render component of nested routes ReactJS

I have nested routes that go 3 levels deep but I'm not able to render the component of my last route. This is how I structured my routes :

<Provider store={store}>
 <Router history={browserHistory}>
   <Route path="/login" component={Login} />
   <Route path="/" name="test" component={requireAuthentication(App)}>
     <Route path="/modules" name="Modules" component={Modules}>
       <Route path="virtual-inputs" name="Virtual Inputs" component={VirtualInput}>
         <Route path="add" name="Add new virtual input" component={AddVirtualInput}/>
       </Route>
     </Route>
   </Route>
 </Router>
</Provider>

When I go to modules/virtual-inputs/add I get my component VirtualInput rendered.

I render inside modules my child components with this.props.children, but how can I render my component AddVirtualInput when going to /modules/virtual-inputs/add ?

I saw already on another thread ( https://stackoverflow.com/a/33690586/846326 ) that another solution is to have my routes like this :

<Route path="/modules" name="Modules" component={Modules}>
  <Route path="virtual-inputs" name="Virtual Inputs" component={VirtualInput}/>
  <Route path="virtual-inputs/add" name="Add new virtual input" component={AddVirtualInput}/>
</Route>

Is this the way to do it, meaning we can't go further then 2 levels?

There is no restriction on the level of nesting of routes in React Router.

When you nest routes, the parent route component will receive the current matching child route component as this.props.children . As long as you don't forget to use this.props.children , they should render just fine.

In your case, it should be enough to make sure that you use this.props.children in the render() method of the VirtualInput component. Otherwise it will receive AddVirtualInput in this.props.children but you won't see it since it doesn't get rendered.

If you already did that, please share the full code of the components to further diagnose the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM