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
Basically, you can use the ? character to make the parameter optional.
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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With