Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional Path React Router 4

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} />

like image 431
pizzarob Avatar asked May 13 '17 01:05

pizzarob


1 Answers

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} />
like image 117
Gapur Kassym Avatar answered Oct 17 '22 19:10

Gapur Kassym