457

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

Community
  • 1
  • 1
tbo
  • 9,398
  • 8
  • 40
  • 51
  • 2
    v6: React router seems to have dropped support for optional path parameters in v6, see https://github.com/remix-run/react-router/issues/7285#issuecomment-620071853 (and the discussion therein). – Chris Chudzicki Jan 14 '22 at 23:20

8 Answers8

833

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.

Community
  • 1
  • 1
Chris
  • 57,622
  • 19
  • 111
  • 137
  • 3
    This is still a question about multiple optional params in URL, like `/route(/:category/(:article)` – Alex Shwarc Jul 31 '17 at 09:59
  • 1
    @AlexShwarc, good point, thanks. I added code to demonstrate multiple optional parameters. Have a look. – Chris Jul 31 '17 at 10:15
  • 2
    @Chris I'm sure, it doesn't work this way, have you checked that? – Alex Shwarc Jul 31 '17 at 15:23
  • @Chris with 3 version – Alex Shwarc Aug 01 '17 at 11:03
  • @Chris Try to check with one parameter supplied, what you get? – Alex Shwarc Aug 01 '17 at 11:25
  • @AlexShwarc Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/150718/discussion-between-chris-and-alex-shwarc). – Chris Aug 01 '17 at 11:41
  • @Chris @AlexShwarc what about this kind of path? Can you help me pls. `/tasks/45/notification/13` where `notification/13` is optional? Tried this `/tasks/:id(/notification/:notId)?` but it does not work! – iamandrewluca Oct 09 '17 at 12:58
  • @Chris ok, thanks! here it is https://stackoverflow.com/questions/46647427/react-router-4-with-optional-path-and-optional-parameter – iamandrewluca Oct 09 '17 at 13:17
  • 1
    Can I create optional path param to the main route ? For example I need add language param to the path, and my homepage url will be "/" and "/en" [Here is demo](https://codepen.io/kholiavko-roman/pen/zpqKaa?editors=1010) – Kholiavko Dec 19 '17 at 11:23
  • Please make sure That your index.html files includes the bundle.js as ` not ` If not, your route with optional param will not load the component – dush88c Feb 10 '20 at 15:04
  • Do you know where I can read up on repeating patterns? – Sam Mar 22 '21 at 23:38
  • @Sam not sure what you mean exactly, but I'm thinking maybe using Regex might interest you? – Chris Mar 23 '21 at 06:52
  • Please note that the version of path-to-regexp supported from react-router is ^1.7.0, which is really old. – ErmannoS Jul 06 '21 at 13:56
  • 7
    @chris Might want to update this answer for v6... Optional path parameters appear not to be supported. See https://github.com/remix-run/react-router/issues/7285#issuecomment-620071853 – Chris Chudzicki Jan 14 '22 at 23:19
  • @ChrisChudzicki Thanks for the heads-up. As I am not using v6 myself, please feel free to update the answer to include v6 – Chris Jan 15 '22 at 00:04
104

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} />
Akash Kumar Verma
  • 3,185
  • 2
  • 16
  • 32
John
  • 3,357
  • 1
  • 17
  • 15
  • @user2928231 Thanks, updated with their new docs url. As far as I can tell `` is now `` again, but the question mark suffix remains the approach now for handling optional params. – John Feb 20 '17 at 12:36
  • 4
    Hi! I still have a problem with optional parameter and can't make next routes working: I have `players`, `players/123`, `players/123/edit`, `players?unseen=true`. The optional parameter `?unseen` doesn't work for me. though I tried all fixes from this discussion. Could you please help with the proper path string, which will handle this? Thanks in advance! – Khrystyna Skvarok Jul 12 '17 at 09:46
  • Hi @KhrystynaSkvarok, did you ever figure out how to get your path w/ an optional query string working? I'm trying to do the same – sabliao Apr 26 '18 at 18:18
  • 2
    @sabliao Hi! I don't have a working example, but for URL like `example.com/search?query=test` try to use next pattern `/:search(search)`. – Khrystyna Skvarok Apr 30 '18 at 20:19
  • How can I get params from url after delimiter? – PHP Ninja Aug 08 '18 at 06:39
  • Please make sure That your index.html files includes the bundle.js as ` not ` If not, your route with optional param will not load the component – dush88c Feb 10 '20 at 15:02
54

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
Nebojsa Sapic
  • 9,285
  • 1
  • 22
  • 23
47

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>
Ivan Talalaev
  • 6,014
  • 9
  • 40
  • 49
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/30973721) – Joosep Parts Feb 08 '22 at 03:59
16

for react-router V5 use below syntax for multiple paths

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

for V6

<Route path="/teams" element={<Teams />}>
  <Route index element={<TeamsIndex />} />
  <Route path=":teamId" element={<Team />} />
</Route>
Nishant Singh
  • 477
  • 4
  • 8
7

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

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} />
Thenlie
  • 674
  • 8
  • 15
  • Since optional parameters have been removed, how are you able to use "?" in your path? – tronman May 03 '22 at 19:02
  • 1
    Thanks for pointing that out. That was actually a typo. The first path renders if there is no third param, the second path renders when there is a third param. – Thenlie May 03 '22 at 23:46
  • 1
    Looks like optional parameters are supported again: https://github.com/remix-run/react-router/issues/9546 – Cristi Nica Feb 11 '23 at 17:30
2

Optional route segments are back in v6.5! https://github.com/remix-run/react-router/issues/9546

user2025261
  • 155
  • 7