'Check if URL param is in list of allowed params and route accordingly

In my app.js, I have a list of Routes:-

  <Switch>
    <Route path='/:locale'>
      <Header />
      <Container />
      <Footer />
    </Route>
    <Route path='/notfound' component={NotFound} />
    <Redirect to='/notfound' />
  </Switch>

I have a URL like www.mydomainname.com/us. I want the first route to render the components only when the :locale matches us or uk. If the :locale is empty or something not equal to us or uk (like au), then the page should route to /notfound.

The problem I am currently facing is, if I enter www.mydomainname.com/notfound or any random stuff after www.mydomainname.com/, then the first route is executing. I know I can get the :locale using useParams(), but how do I check it against an array of allowed values and reroute to the /notfound page if the check fails?



Solution 1:[1]

The route "/:locale" is a catch all route, so it will match any "/randomstring". Introduce a component Body which is a locale specific renderer.

<Switch>
<Route path='/notfound' component={NotFound} />
<Route path='/:locale'>
  <Body>
    <Header />
    <Container />
    <Footer />
  <Body>
</Route>
<Redirect from='/' to='/notfound' exact />
</Switch>

And Body component will be handling redirect

const Body = (props) => {
  const { locale } = useParams()
  if (["us", "uk"].indexOf(locale) != -1)
    return(props.children)
  else
    return(
      <Redirect to="/notfound" />
    )
}

Solution 2:[2]

The react-router-dom@5 Route component's path prop uses path-to-regexp under the hood, so you can use this to more exactly match paths. path="/:locale(us|uk)" will only match "/us" and "/uk" paths.

Example:

<Switch>
  <Route path="/:locale(us|uk)">
    <Header />
    <Container />
    <Footer />
  </Route>
  <Route path="/notfound" component={NotFound} />
  <Redirect to="/notfound" />
</Switch>

Edit check-if-url-param-is-in-list-of-allowed-params-and-route-accordingly

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sh4dy
Solution 2