Reputation: 6248
React router renders both Foo
and FooBar
for the route /foo/bar
ReactDOM.render(
(<BrowserRouter>
<div>
<Route path="/foo/bar" component={FooBar}/>
<Route path="/foo" component={Foo}/>
</div>
</BrowserRouter>)
, document.getElementById("root"));
Why on earth would it run both routes? I think this is insane.
How would I use nested routes (without :/params
in case I want to do more than one nested route? Such as /foo/bar/baz/whatever
?).
Would an answer to this question even make sense without mentioning which version I'm on?
Upvotes: 2
Views: 1743
Reputation: 12071
With React Router V4, you can use the Switch component to ensure only the first matched route is rendered:
import { Switch, Route } from 'react-router-dom'
...
<Switch>
<Route path="/foo/bar" component={FooBar}/>
<Route path="/foo" component={Foo}/>
</Switch>
You could also use the exact prop to ensure the /foo route is only matched when the url is /foo and not /foo/bar:
<Route path="/foo" exact component={Foo}/>
<Route path="/foo/bar" component={FooBar}/>
Upvotes: 2