React Router: Route defined in child component not working
React Router: Route defined in child component not working
I'm working on a React web application using React router.
The Route objects defined on the main wrapper component are working just fine, but if I try to define a Route on a child component, any link pointing to it won't be able to render the desired component.
Here is a code snippet trying to explain the situation:
class MainWrapper extends Component
render()
return (
<div className="App">
<Switch>
<Route exact path="/a" component= A/>
</Switch>
</div>
);
const A = () =>
return (
<div>
<Route exact path="/b" component=B/>
<Link to="/b"/>
</div>
)
const B = () =>
return (<div>HELLO</div>)
In my application, the link pointing to "/b" is not rendering the B component, like the component prop weren't passed
Why this won't work?
4 Answers
4
You are specifying "exact path" in both Routes, so for rendering B your path should be exactly "/b", but when linking to "/b" component A will unmount because for rendering A you must be on exact path "/a". You should change your approach. One would be removing "exact" and including "/a" to your Link:
class MainWrapper extends Component
render()
return (
<div className="App">
<Switch>
<Route path="/a" component= A/>
</Switch>
</div>
);
const A = () =>
return (
<div>
<Route path="/b" component=B/>
<Link to="/a/b"/>
</div>
)
const B = () =>
return (<div>HELLO</div>)
if B is a child of A, the url should be /a/b instead of /b, so you just need to update the A component with this code
/a/b
/b
A
const A = (match) =>
return (
<div>
<Route exact path=`$match.url/b` component=B/>
<Link to=to=`$match.url/b`/>
</div>
)
;
See the documentation here
Do you have a Router somewhere? Also, you haven't closed your Link tag.
Router
Link
You need to wrap it in a Switch, and you should remove the exact prop from your /b route.
Switch
exact
/b
const A = (match) =>
return (
<div>
<Switch>
<Route path=`$match.url/b` component=B/>
</Switch>
<Link to="a/b"/>
</div>
)
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Yes, I do have a Router defined somewhere (on a parent component of MainWrapper). I'll correct the typo in the snippet (this is not the real code, which is compiling just fine)
– Adriano Todaro
Aug 31 '18 at 19:20