Home > Enterprise >  Check if URL param is in list of allowed params and route accordingly
Check if URL param is in list of allowed params and route accordingly

Time:03-30

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?

CodePudding user response:

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>
</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" />
    )
}
  • Related