Note: React Router v4 is incompatible with react-router-relay (read more here). Use version v3 or earlier (v2 recommended) instead.
React Router v1, v2 and v3
Since version 1.0.0
you define optional parameters with:
<Route path="to/page(/:pathParam)" component={MyPage} />
and for multiple optional parameters:
<Route path="to/page(/:pathParam1)(/:pathParam2)" 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.
Note: The :paramName
parameter matches a URL segment up to the next /
, ?
, or #
. For more about paths and params specifically, read more here.
React Router v4 and above
Check the React Router v6 documentation for Optional Segments
.
React Router v4 is fundamentally different than v1-v3, and optional path parameters aren't explicitly defined in the official documentation either.
You are instructed to define a path
parameter that path-to-regexp understands. This allows for much greater flexibility in defining your paths, such as repeating patterns, wildcards, etc. So to define a parameter as optional you add a trailing question-mark (?
).
As such, to define an optional parameter, you do:
<Route path="/to/page/:pathParam?" component={MyPage} />
and for multiple optional parameters:
<Route path="/to/page/:pathParam1?/:pathParam2?" component={MyPage} />