[javascript] 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

This question is related to javascript reactjs react-router react-router-v4

The answer is


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 (read more here). Use version v3 or earlier (v2 recommended) instead.


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

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

for react-router V5 and above use below syntax for multiple paths

<Route
          exact
          path={[path1, path2]}
          component={component}
        />

Working syntax for multiple optional params:

<Route path="/section/(page)?/:page?/(sort)?/:sort?" component={Section} />

Now, url can be:

  1. /section
  2. /section/page/1
  3. /section/page/1/sort/asc

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to react-router

React : difference between <Route exact path="/" /> and <Route path="/" /> You should not use <Link> outside a <Router> React Router Pass Param to Component Detect Route Change with react-router What is the best way to redirect a page using React Router? No restricted globals React-router v4 this.props.history.push(...) not working How to pass params with history.push/Link/Redirect in react-router v4? How to use Redirect in the new react-router-dom of Reactjs How to implement authenticated routes in React Router 4?

Examples related to react-router-v4

react-router (v4) how to go back? Detect Route Change with react-router How to implement authenticated routes in React Router 4? How to push to History in React Router v4? Changing the URL in react-router v4 without using Redirect or Link React Router v4 - How to get current route? Programmatically navigate using react router V4 How to listen to route changes in react router v4? Nested routes with react router v4 / v5 React Router with optional path parameter