tbo tbo - 1 month ago 21
React JSX Question

React Router with optional path parameter

I want to declare a path with an optional path parameter, hence when I add it the page to do something extra (e.g. fill some data):


http://localhost/app/path/to/page <= render the page
http://localhost/app/path/to/page/pathParam <= render the page with
some data according to the pathParam


In my react router I have the following paths, in order to support the two options (this is a simplified example):

<Router history={history}>
<Route path="/path" component={IndexPage}>
<Route path="to/page" component={MyPage}/>
<Route path="to/page/:pathParam" component={MyPage}/>
</Route>
</Router>


My question is, can we declare it in one route? If I add only the second row then the route without the parameter is not found.

EDIT#1:

The solution mentioned here about the following syntax did not work for me, is it a proper one? Does it exist in the documentation?

<Route path="/product/:productName/?:urlID?" handler={SomeHandler} />


My react-router version is: 1.0.3

Answer

The edit you posted was valid for an old version of React-router (v0.13).

As of version 1.0.0 (including version 2.x) you do it with:

<Route path="to/page(/:pathParam)" component={MyPage} />

You use parenthesis ( ) to wrap the optional parts of route, including the leading slash (/). Check out the Route Matching Guide page of the official documentation.


Example

Assume the following route:

<Route path="to/page(/:pathParam)" component={MyPage} />

This route will match the following paths:

  • to/page - will match. :pathParam is equal to null (as it's not provided in the path).
  • to/page/example - will match. :pathParam is equal to example.

Notes

The :paramName parameter matches a URL segment up to the next /, ?, or #.

  • to/page/another/example - will not match (this path requires 2 parameters).
  • to/page/another#example - will match, but :pathParam will be equal to another.
  • to/page/another?example - will match, but :pathParam will be equal to another.

For more about paths and params specifically, read more here.

Comments