10

Let's say I have the following 2 routes:

    ...
    <Route exact path="/:param1?/" component={Home}/>
    <Route path="/news" component={News}/>
    ...

now when I try to hit route /news the root route for Home with the parameter param1 is triggered...

I assume the solution would be to set a questionmark before the param1 like this /?param1 so it can be held appart from the routes, but I can not figure out how to do this in react-router v4

henk
  • 2,677
  • 2
  • 18
  • 49
  • 1
    Possible duplicate of [React Router with optional path parameter](http://stackoverflow.com/questions/35604617/react-router-with-optional-path-parameter) – Chris Mar 16 '17 at 08:20
  • absolutely not, I know how to set optional parameter, (which is the question in your link)! My question is more about how to differentiate between the parameter and another route... see the answer below... – henk Mar 17 '17 at 12:34
  • Alright... just trying to help :) – Chris Mar 17 '17 at 12:35

1 Answers1

14

There's an example of how to do this in the official docs. You can find that here.

You'll need to use the Switch component with your /news Route being first.

<Switch>
    <Route path="/news" component={News}/>
    <Route exact path="/:param1?/" component={Home}/>
</Switch>

Switch will always only render one Route. So in the case above, if /news doesn't become active, then /:param1 will be.

Tyler McGinnis
  • 34,836
  • 16
  • 72
  • 77
  • 1
    Hey man, could you please help me how to create router for homepage with optional path (for example language) I try something like this: ` ` but in this case the second route does not work correctly without language params. – Kholiavko Dec 17 '17 at 16:52