Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router - how to constrain params in route matching?

I don't really get how to constrain params with, for example a regex.
How to differentiate these two routes?

  <Router>     <Route path="/:alpha_index" component={Child1} />     <Route path="/:numeric_index" component={Child2} />   </Router> 

And prevent "/123" from firing the first route?

like image 721
Sifnos Avatar asked May 17 '16 07:05

Sifnos


1 Answers

React-router v4 now allows you to use regexes to match params -- https://reacttraining.com/react-router/web/api/Route/path-string

const NumberRoute = () => <div>Number Route</div>; const StringRoute = () => <div>String Route</div>;  <Router>     <Switch>         <Route exact path="/foo/:id(\\d+)" component={NumberRoute}/>         <Route exact path="/foo/:path(\\w+)" component={StringRoute}/>     </Switch> </Router> 

More info: https://github.com/pillarjs/path-to-regexp/tree/v1.7.0#custom-match-parameters

like image 157
Sean D. Avatar answered Oct 01 '22 14:10

Sean D.