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?

4
  • 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 Commented Dec 7, 2017 at 22:54
  • You may find this of interest stackoverflow.com/a/35604855/1915893 Commented Dec 7, 2017 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! Commented Dec 7, 2017 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. Commented Dec 7, 2017 at 23:05

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.