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

3
  • 1
    Possible duplicate of React Router with optional path parameter Commented Mar 16, 2017 at 8: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... Commented Mar 17, 2017 at 12:34
  • Alright... just trying to help :) Commented Mar 17, 2017 at 12:35

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey man, could you please help me how to create router for homepage with optional path (for example language) I try something like this: <Switch> <Route exact path="/:language?" component={FirstPage} /> <Route exact path="/:language?/add" component={AddPage} /> </Switch> but in this case the second route does not work correctly without language params.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.