16

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} />
sylvain
  • 1,951
  • 2
  • 19
  • 34
  • Does this answer your question? [Multiple path names for a same component in React Router](https://stackoverflow.com/questions/40541994/multiple-path-names-for-a-same-component-in-react-router) – Ben Smith Jan 14 '22 at 01:02

4 Answers4

22

Best solution I found so far (but seems a bit strange) :

<Route path="/:path(path1|path2)" component={MyComp} />
sylvain
  • 1,951
  • 2
  • 19
  • 34
12
<Route path={["/common-one", "/common-two"]} component={Common} />

For version 5 above https://reactrouter.com/web/api/Route

8

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 :).

Vladimir Syeik
  • 185
  • 2
  • 7
1

If you need to allow multiple match (different parameters) but also without parameter - e.g. match URLs:

  • /questions
  • /questions/posted
  • /questions/answered

You can do this with optional parameter (note question mark after the bracket)

<Route path="/questions/:tab(posted|answered)?" component={...} />
webit
  • 99
  • 2
  • 10