reactjsreact-routerreact-router-componentreact-routing

Send both 404 status and redirect to 404 component in react-router


I have a react-router 3.0.0 setup with a NotFound component I'm showing as a fallback:

<Route component={NotFound} path="*"/>

However this returns a redirect and the google crawler is complaining about soft 404s. Can I both redirect to my NotFound component and send a 404, similar to what Github does for instance? I've tried the following suggestion from here: How to let react router respond with 404 status code?

<Route component={NotFound} path="*" status={404}/>

But that just gives me a 404 without displaying the component.

How can the above be accomplished?


Solution

  • React Router v6

    Live Demo: Redirect Default or 404 Routes with React Router

    Example code:

    <Router>
      <Routes>
        <Route path="users" element={<Users />} />
        <Route path="posts" element={<Posts />} />
      </Routes>
    </Router>
    

    To redirect and navigate to one of our chosen routes, we can use component from React Router. Now we can declare below our route configuration the case for empty routes, like this:

    <Router>
      <Routes>
        <Route path="users" element={<Users />} />
        <Route path="posts" element={<Posts />} />
        <Route path="" element={<Navigate to="/users" />} />
      </Routes>
    </Router>