Given I have 2 path rendering the same component, how do I avoid to repeat route configs like this :
<Route path="/path1" component={MyComp} />
<Route path="/path2" component={MyComp} />
Given I have 2 path rendering the same component, how do I avoid to repeat route configs like this :
<Route path="/path1" component={MyComp} />
<Route path="/path2" component={MyComp} />
Best solution I found so far (but seems a bit strange) :
<Route path="/:path(path1|path2)" component={MyComp} />
<Route path={["/common-one", "/common-two"]} component={Common} />
For version 5 above https://reactrouter.com/web/api/Route
Great answer. This also helps in the following scenario:
<Route path="/path/path1" component={MyComp} />
<Route path="/path/:subpath(path2|path3)" component={MyAnotherComp} />
Without (path2|path3)
both components MyComp
and MyAnotherComp
are mounted if the path is /path/path2
.
PS. Would have added as a comment, but not eligible :).
If you need to allow multiple match (different parameters) but also without parameter - e.g. match URLs:
You can do this with optional parameter (note question mark after the bracket)
<Route path="/questions/:tab(posted|answered)?" component={...} />