2

React Router 4.0.0 comes with Regex to validate the querystring parameters. However, it does not seem compatible with ES6 Template Literals.

Here is a very simple example :

<BrowserRouter>
  <Switch>
    <Route Route path={routeConstant} component={MyComponent} />
  </Switch>
</BrowserRouter>

If you try with the following values, you'll see that the first 2 constants work, but the third does not.

const root = 'folder'
const routeConstant1 = '/folder/:id(\d+)'  // <= /folder/21 matches
const routeConstant2 = `/${root}/:id`      // <= /folder/21 matches
const routeConstant3 = `/${root}/:id(\d+)` // <= /folder/21 does not match

There is probably a very good explanation (there always is), but I'd really appreciate a few pointers because that feels a bit confusing. Thanks in advance.

1 Answer 1

2

Ok, I posted that question too fast I guess.

The answer is in the way Template Literals work : ECMAScript 6 - Template Literals

=> "backslashes are not interpreted"

So the solution to have routeConstant3 work is simply to write it like this :

const routeConstant3 = `/${root}/:id(\\d+)`
Sign up to request clarification or add additional context in comments.

1 Comment

It knows /folder/21 but /folder/21abc should be an invalid route, which is where this check fails and react router attempts to render invalid route.

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.