Home > Software design >  React Router prevent random route
React Router prevent random route

Time:09-26

How would I structure a React-Router switch statement to prevent anything from happening if the user enters an unmatched route? In other words, I don't want a 404 not found page; I just want nothing to happen and the current url doesn't change.

Here's my switch statement:

 <Switch>
    <Route path="/" exact>
      <LandingPage />
    </Route>
    <Route path="/login" exact>
      <LandingPage />
    </Route>
    <Route path="/new-account" exact>
      <LandingPage />
    </Route>

    <Route path="/account-settings" exact>
      <AccountSettings />
    </Route>

   
    <Route path="/dashboard" exact>
      <Dashboard userStatus={userStatus} />
    </Route>
    
    <Route path={"*"}>
      {/* Could I somehow achieve this here? */}
    </Route>
  </Switch>

CodePudding user response:

You can use the Redirect component of react-router-dom to redirect the user whenever he hits an unknown endpoint.

CodePudding user response:

you can implement another page(view) with a custom hook and place it here:

    <Route path={"*"}>
      {/* Could I somehow achieve this here? */}
    </Route>

new component for your * routes:

function RedirectHook() {
  history = useHistory() // which imported from react-router-dom
  useEffect(() => {
    history.goBack();
  })

  return null
}

now every page that does not exist on your routes list will be pushed to RedirectHook and then sent back to the original page.

  • Related