Redirect to Home page if URL not found

Viewed 48

For following scenario, I have to redirect to home page if entered url not found.

When user try to access page which is not available, it should redirect to home page or error page. CODE: *

function App() {
  return (
    <div className="app">
      <Suspense fallback={<div>Loading...</div>}>
        <Router history={history}>
          <Header />
          <div className="app-container">
            <Switch>
              {routes.map(
                ({ key, path, crumbs, renderComponent }) => {
                  return (
                    <Route key={key} path={path}>
                      {renderComponent(crumbs)}
                    </Route>
                  )
                }
              )}
              <Redirect exact from="/" to="/merchants" />
            </Switch>
          </div>
          <div className="footer-wrapper">
            <div className="footer">
              <footer max-width="1920"></footer>
            </div>
          </div>
        </Router>
      </Suspense>
    </div>
  )
}
1 Answers

Add another Redirect that handles any route path that wasn't handled above it by a Route or Redirect component rendering on a more specific path.

<Switch>
  {routes.map(({ key, path, crumbs, renderComponent }) => (
    <Route key={key} path={path}>
      {renderComponent(crumbs)}
    </Route>
  ))}
  <Redirect exact from="/" to="/merchants" />
  <Redirect to="/" />
</Switch>

Since it seems the "/merchants" route is your default homepage you can remove the exact and to props and handle any route path that wasn't handled previously.

<Switch>
  {routes.map(({ key, path, crumbs, renderComponent }) => (
    <Route key={key} path={path}>
      {renderComponent(crumbs)}
    </Route>
  ))}
  <Redirect to="/merchants" />
</Switch>
Related