3

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?

2 Answers 2

6

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 } /> } 
/>
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.