How do I match an optional path using the Route
component in React Router 4?
For example I have an Orders
component that I want to render on both /account and /account/orders.
The equivalent would be having two Route components to match both paths.
<Route exact path="/account" component={Orders} />
<Route exact path="/account/orders" component={Orders} />
You can use path param optional on react-router 4 like that:
<Route exact path="/account" component={Orders} />
<Route exact path="/account/orders?" component={Orders} />
So to define a parameter as optional you add a trailing question-mark (?). Also for multiple optional parameters:
<Route path="/account/:pathParam1?/:pathParam2?" component={Orders} />
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