Sifnos
Sifnos

Reputation: 1171

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?

Upvotes: 48

Views: 33256

Answers (2)

Sean D.
Sean D.

Reputation: 1071

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

Upvotes: 86

hansn
hansn

Reputation: 2024

I'm not sure if this is possible with React router at the moment. However there's a simple solution to your problem. Just do the int/alpha check in another component, like this:

<Router>
    <Route path="/:index" component={Child0} />
</Router>

const Child0 = (props) => {
    let n = props.params.index;
    if (!isNumeric(n)) {
        return <Child1 />;
    } else {
        return <Child2 />;
    }
}

* Note that the code above does not run, it's just there to show what I mean.

Upvotes: 9

Related Questions