Kuzma
Kuzma

Reputation: 711

React Router V4 allow only certain parameters in URL

I'm using the React Router V4 and I've this router's configuration:

  <Router history={customHistory}>
    <Switch>
      <Route exact path={`/:lng?`} component={Page} />
      <Route path={`/:lng?/firstUrl`} component={Page}/>
      <Route path={`/:lng?/secondUrl`} component={Page}/>
      <Route component={NoMatch} />
    </Switch>
  </Router>

The lng is optional language parameter which should match pattern like a en, de or absent. For instance app utilizes these routes:

www.website.com/en
www.website.com/en/
www.website.com/  - will load default lang
www.website.com  - will load default lang
www.website.com/de
www.website.com/de/

Also I've additional component inside which I define routes for functions:

  <ModalRoute component={SomeURL} path={`/:lng?/SomeURL`} parentPath={`/${lang}/`} />
  <ModalRoute component={SomeURL2} path={`/:lng?/SomeURL2`} parentPath={`/${lang}/`} />

So as the result I would like to achieve that only allowed language codes (and empty param) would be accepted and which don't - would be redirected to NoMatch component.

Is it possible? How it could be achieved?
Example much appreciated

Upvotes: 8

Views: 6025

Answers (1)

U Rogel
U Rogel

Reputation: 1941

You can use regex in your path.

For a required parameter with specified options:

<Route path="/about/:lang(en|de)/" exact component={About}/>

For an optional paramater:

<Route path="/about/:lang?/" exact component={About}/>

For an optional parameter with specified options

<Route path="/about/:lang(en|de)?/" exact component={About}/>

For further reading

Upvotes: 22

Related Questions