0

FYI, I am using React Router 5. I have following dependency in my package.json:

"react-router-dom": "^5.0.0",

[ Question edited with a more simplified example ]

Let me describe the issue I am facing. All the following URLs

http://localhost:3001/contact
http://localhost:3001/contact/
http://localhost:3001/contact/john50

are matching following route ( with 1 optional param )

<Route path="/contact/:name([A-Za-z]+)?" component={Contact} />

JSfiddle for above behaviour.

Then, I have updated the above Route by adding another optional param, age. It looks like this:

<Route path="/contact/:name([A-Za-z]+)?:age(\d{2})?" component={Contact} />

Why this new updated route with 2 optional params is matched by this URL :

http://localhost:3001/contact/

and not by this URL :

http://localhost:3001/contact

Jsfiddle for this weird behaviour

Why ? Can someone explain ?

Arun Kandregula
  • 655
  • 3
  • 8
  • 18

2 Answers2

0

You must wrap the param along with / within the optional regex by wrapping it within ()

<Route path="/about/:param1(\d{2}-\d{2}-\d{4})?/:param2(\.[A-Za-z]+)?" component={About} />

Note: Params need to separted by / which you don't have. You can have your Route like

<Route path="/about/:param1(\d{2}-\d{2}-\d{4})?/:param2(\.[A-Za-z]+)?" component={About} />

and then your Navigation links will be

const Navigation = () => (
    <ul className="navLinks">
      <li><NavLink  to="/">Home</NavLink></li>
      <li><NavLink to="/contact/john/50">Working Contact</NavLink></li>
      <li><NavLink to="/contact/">Contact With Slash</NavLink></li>
    <li><NavLink to="/contact">Contact Without Slash</NavLink></li>
    </ul>
);

Working demo

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
0

Try this,

<Route path="/contact/:name?/:age?" component={Contact} />

Also see this & this

ravibagul91
  • 20,072
  • 5
  • 36
  • 59
  • Hi @ravibagul91 I have added JSfiddle examples. I dont have / between name and age. – Arun Kandregula May 03 '19 at 08:35
  • @ArunKandregula If you don't have / between name and age, then you need to manually split it. – ravibagul91 May 03 '19 at 08:47
  • I am already doing that. I am manually splitting using reg exp. Its working fine for the best case. Say /contact/John50. Its happily splitting John and 50. The question is why /contact and /contact/ are behaving differently when dealing with 2 optional params with out /. – Arun Kandregula May 03 '19 at 17:12