Search code examples
javascriptreactjsreact-routercoercion

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?


Solution

  • 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>