pizzarob
pizzarob

Reputation: 12029

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

Upvotes: 5

Views: 6817

Answers (2)

Gapur Kassym
Gapur Kassym

Reputation: 1201

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

Upvotes: 8

pizzarob
pizzarob

Reputation: 12029

I can do the following to match both paths:

<Route exact path="/account/(orders)?" component={Orders} />

Upvotes: 6

Related Questions