score:798
The edit you posted was valid for an older version of React-router (v0.13) and doesn't work anymore.
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
React Router v4 is fundamentally different than v1-v3, and optional path parameters aren't explicitly defined in the official documentation either.
Instead, 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} />
Note: React Router v4 is incompatible with react-router-relay (read more here). Use version v3 or earlier (v2 recommended) instead.
score:0
If you are looking to do an exact match, use the following syntax:
(param)?
.
Eg.
<Route path={`my/(exact)?/path`} component={MyComponent} />
The nice thing about this is that you'll have props.match
to play with, and you don't need to worry about checking the value of the optional parameter:
{ props: { match: { "0": "exact" } } }
score:4
As Sayak pointed out, optional parameters have been removed from React Router V6. The easiest solution I have found was to just make two routes. One for the url without the param and one with:
<Route path="/product/:productName/" handler={SomeHandler} />
<Route path="/product/:productName/:urlID" handler={SomeHandler} />
score:5
As with regular parameters, declaring an optional parameter is just a matter of the path property of a Route; any parameter that ends with a question mark will be treated as optional:
<Route path="to/page/:pathParam?" component={MyPage}/>
score:11
Well since you have mentioned your react-router version as 1.0.3 you can find your solution among the previous answers.
However from React Router v6 this option has been removed as mentioned. here
Hence for React Router v6 the following :
<Route path='/page/:friendlyName/:sort?' element={<Page/>} />
will be replaced by :
<Route path='/page/:friendlyName/:sort' element={<Page/>} />
<Route path='/page/:friendlyName/' element={<Page/>} />
or you can also use :
<Route path="/page/:friendlyName">
<Route path=":sort" element={<Page />} />
<Route path="" element={<Page />} />
</Route>
score:13
for react-router V5 and above use below syntax for multiple paths
<Route
exact
path={[path1, path2]}
component={component}
/>
score:46
Working syntax for multiple optional params:
<Route path="/section/(page)?/:page?/(sort)?/:sort?" component={Section} />
Now, url can be:
- /section
- /section/page/1
- /section/page/1/sort/asc
score:100
For any React Router v4 users arriving here following a search, optional parameters in a <Route>
are denoted with a ?
suffix.
Here's the relevant documentation:
https://reacttraining.com/react-router/web/api/Route/path-string
path: string
Any valid URL path that path-to-regexp understands.
<Route path="/users/:id" component={User}/>
https://www.npmjs.com/package/path-to-regexp#optional
Optional
Parameters can be suffixed with a question mark (?) to make the parameter optional. This will also make the prefix optional.
Simple example of a paginated section of a site that can be accessed with or without a page number.
<Route path="/section/:page?" component={Section} />
Source: stackoverflow.com
Related Query
- React Router with optional path parameter
- React Router 4 with optional path AND optional parameter
- React Router 4 Optional parameter with custom path
- Simple React Router with an Optional Path Parameter gives 'TypeError: Cannot read property 'filter' of undefined'
- React router 4, path with parameter
- React Router - path with regular expression and parameter not equal to a string
- How to create optional parameter on path and activestyle in react router v4/react-router-dom?
- React router v5 create a path with two optional params
- Match multiple path with react router v4
- Exclude a value for a path parameter in React Router by type
- React Router v4 components with similar paths (fixed and dynamic path param) are "overlapping"
- React Router with relative path deployment
- How to set route with optional query parameter using React router?
- Optional Path React Router 4
- React Router 4 and exact path with dynamic param
- Get react router path in props with redux ownProps
- How to retrieve the parameter after a hash (#) with React Router and useParams hook?
- react router routing with parameter id
- Pass extra parameter with the react router definition
- ReactJS -How to create multistep component/form with single path using React Router
- Redirect to Parent Route with Parameter in React Router
- How to match ambiguous path and static path with React Router
- React router with basename also matches routes without the base path
- React Router URL Throws Error With Parameter
- How can I add multiple path for home page with react router dom 6?
- How to setup React Router in a sub folder with an ambiguous path
- How to make path param to be optional in react router dom(v4)?
- Passing optional parameter in react router
- React router same path with other query Param
- React Router Unable to navigate with Path parameters
More Query from same tag
- How to use href(redirect to different link) in reactjs?
- Can't call any fineUploader methods in callback function
- Render a component within a component from onClick event in Reactjs
- How can I add/override Footer component in React material-table?
- How do I handle API calls in React lifecycle methods?
- ReactJS: How to set disabled option in a dynamic way for sortableJS?
- My React Router <Link to> is activating multiple links
- SCSS styles imported to components in app.js are being applied to all components in app.js
- React tutorial: CommentForm's onSubmit not working
- React: how can I call a function when a component has loaded?
- re-render the state after changing a part of the data - reactjs
- How to disable a dates in one calender between two dates based on a selection using antd?
- React: Get DOM data from sibling elements
- Nesting a container component in a presentational component
- Rating star field in a material ui/redux-form framework
- 'i18next-http-backend' module couldn't be load
- Rechart Bar Chart: show nothing except the bar? (fullwidth and fullheight?)
- How to convert functional component using hooks to class component
- Passing props to reactjs material ui modal
- React Datepicker RangeError: Invalid time value
- How to split the html string and get different tag with values
- JSX syntax error on PHPStorm
- React, TypeScript: How define the parameters of handler in a child component?
- Apollo Mutation does not recognize variables
- webpack config for bootstrap fonts in react
- Argument of type 'Response' is not assignable to parameter of type 'SetStateAction`
- I am getting a void returned when trying to dynamically import images from a directory using webpack
- Async React.Component doens't work for me
- replace an object inside an array with reducer
- Efficient way to request back-end for data on input change