Reputation: 487
Let's take this example
{/* NESTED ROUTES */}
<Route path={`${match.url}/:topicId`} component={Topic}/>
<Route exact path={match.url} render={() => (
<h3>Please select a topic.</h3>
)}/>
Nested routes work fine. However, how can I nest a Route within a nested route? For example:
path={`${match.url}/:topicId/edit`} component={EditTopic}
Is there a good/bad practice guide for how many levels you would nest? Any tips/guidance is appreciated!
Upvotes: 0
Views: 588
Reputation: 266
how can I nest a Route within a nested route?
React Router v4 encourages you to think of Route
just like any other component. It helps you compose your interface depending on what is happening in the url.
So - you shouldn't feel weird about nesting Route
s or using them deep in your component tree to modify the interface in response to the url.
In your example, you could have further nested Route
s either in the Topic
component or in the function passed down as a render
prop.
Is there a good/bad practice guide for how many levels you would nest?
This is a great question. Like so many other things, it comes down to taste. Be guided by making your code easy to understand for others and for yourself in six months time.
In some cases, it might be simplest to take the old fashioned approach and keep all your routes in one component. In other cases, it will be better to use four levels of nesting.
In my team, we have adopted v4 and use several layers of nesting. Along the way we had a lot of conversations to make sure everyone was clear on the approach.
Caution: If you use deep nesting in conjunction with e.g. redux connect
or react PureComponent
, be aware that these might block location updates to your nested Route
s. You'll know this is happening when your Route
doesn't respond to changes in the url. Use withRouter
to solve this.
Upvotes: 1
Reputation: 281626
Instead of using match.url
, you need to use match.path
for building nested routes. According to match
documentation
path - (string) The path pattern used to match. Useful for building nested
<Route>s
url - (string) The matched portion of the URL. Useful for building nested
<Link>s
Upvotes: 0