Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional React Router parameter

Tags:

react-router

I'm trying to create a route that matches all of the following URLs:

/product/foo
/product/foo/bar

Here's my current route:

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

According to the documentation on https://github.com/rackt/react-router/blob/master/docs/guides/basics/RouteMatching.md this route should match perfectly but it does not match either of the URLs above.

What do I need to do to support this optional parameter?

I'm on React Router version 0.13.3 and if I remove the (/:urlID) then I can match the first URL but not the second.

like image 497
Andrew Rasmussen Avatar asked Sep 25 '15 02:09

Andrew Rasmussen


People also ask

Which character lets us create optional route params?

Basically, you can use the ? character to make the parameter optional.

How do you pass optional props in react?

To set optional props with default values in React TypeScript: Mark the props on the type as optional using a question mark. Provide default values for the props when destructuring them in the function's definition.

How do you use useParams in react router Dom?

Step 1: Create a React application using the following command. Step 2: After creating your project folder i.e. useparams_react, move to it using the following command. Step 3: After creating the ReactJS application, Install the react-router-dom and react-dom packages using the following command.


1 Answers

Okay so the () syntax is specific to React Router 1.0, not 0.13.3. I ended up using the ? syntax:

<Route path="/product/:productName/?:urlID?" handler={SomeHandler} />
like image 57
Andrew Rasmussen Avatar answered Jan 01 '23 18:01

Andrew Rasmussen