Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set an optional parameter on root route in react-router v4?

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

like image 489
henk Avatar asked Mar 16 '17 06:03

henk


People also ask

Which character lets us create optional route params?

Basically, you can use the ? character to make the parameter optional.

How do I restrict access to routes in react router?

To restrict access to routes in React Router, we set the render prop to a function that renders the component we want according to the condition we're checking. import { Route, Redirect } from "react-router"; <Route exact path="/" render={() => (loggedIn ?


1 Answers

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.

like image 134
Tyler McGinnis Avatar answered Oct 07 '22 09:10

Tyler McGinnis