15

I'm a bit stuck with the route component. Imagine I have this two Routes with their own path:

<Route path='/person/add' exact component={PersonForm}/>
<Route path='/person/:id' exact component={PersonView}/>

/person/add should show a form where I can create a new Person
/person/:id should show a person with the given id.

The problem >> If I navigate to /person/add it will also show the component of /person/:id because the string "add" is valid for ":id".

Is there a way I can avoid this? For example by telling that :id should be a number?

Aluan Haddad
  • 29,886
  • 8
  • 72
  • 84
Wannes
  • 1,019
  • 2
  • 11
  • 18
  • 1
    `/person/add` should just be `/person` then the state where there is no parameter is the add state and you can reuse it for editing. It makes sense :p – Aluan Haddad Dec 07 '17 at 22:54
  • You may find this of interest https://stackoverflow.com/a/35604855/1915893 – Aluan Haddad Dec 07 '17 at 22:57
  • 1
    @AluanHaddad That's indeed how I solved it, but still I was questioning if there is another solution for it. Thanks! – Wannes Dec 07 '17 at 23:02
  • I see. I'm sure there is a way but determining what strings are valid numbers in JavaScript is a source of much consternation. – Aluan Haddad Dec 07 '17 at 23:05

2 Answers2

28

Found a possible solution: You can use Switch around the routes. Then it will only match on the first one that matches.

<Switch>
  <Route path='/person/add' exact component={PersonForm}/>
  <Route path='/person/:id' exact component={PersonView}/>
</Switch>
Wannes
  • 1,019
  • 2
  • 11
  • 18
0

The problem I was having is that I had several routes;

/locations/:locationId
/locations/new

But when using the matchPath function from react-router it would return a false-positive for /locations/:locationId when I was on /locations/new. I solved this by passing a custom regex to my identifier;

/locations/:locationId([a-z0-9-]{36})

This will check if my "locationId" is a uuid and otherwise it won't match. It's probably also possible to exclude words like "new/edit/add"

enter image description here

These sources helped me;

Simon Somlai
  • 856
  • 8
  • 16