user6177539
user6177539

Reputation:

React Router 4 Optional parameter with custom path

I have this route below that loads a dashboard component:

<Route
  path={`${match.url}/dashboard`}
  render={params => <Dashboard {...params} />}
/>

Now, I want to add an optional parameter that would only be valid if it's being preceded by an additional path (e.g. additional-path/:param). I tried the code below but I'm not getting the value of the optional param:

<Route
  path={`${match.url}/dashboard/(filter/:filtername)?`}
  render={params => <Dashboard {...params} />}
/>

Could somebody tell me whats wrong with the code below?

Upvotes: 3

Views: 6872

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: 0

Steve Holgado
Steve Holgado

Reputation: 12071

In older versions of React Router you would define optional parameters with parentheses, for example: `${match.url}/dashboard/filter(/:filtername)`

For React Router V4 you define the optional filtername parameter with a trailing ? like this:

<Route 
  path={ `${match.url}/dashboard/filter/:filtername?` } 
  render={ params => <Dashboard { ...params } /> } 
/>

Or you can define multiple optional parameters, filter and filtername, like this:

<Route 
  path={ `${match.url}/dashboard/:filter?/:filtername?` } 
  render={ params => <Dashboard { ...params } /> } 
/>

Upvotes: 6

Related Questions