Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude a value for a path parameter in React Router by type

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?

like image 779
Wannes Avatar asked Dec 07 '17 22:12

Wannes


1 Answers

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>
like image 186
Wannes Avatar answered Sep 24 '22 15:09

Wannes