2

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>
1
  • 1
    What if the user starts on a non-existent page and no previous page exists? Commented Sep 25, 2021 at 12:24

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

tried this and it worked quite well
1

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

1 Comment

this answer was flagged for low quality, please better the answer with more supporting info and an explanation

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.