7

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?

paqash
  • 2,294
  • 1
  • 17
  • 22
  • 2
    If you want to return a HTTP 404 status, you'll need to do this from the server. You can use `match` for this. If the match fails you can return a 404 status in the response. http://knowbody.github.io/react-router-docs/api/match.html – cheersjosh Feb 15 '17 at 01:20
  • 1
    Check out the other response in that same question you linked. http://stackoverflow.com/a/36075450/2030321 Taion is actually one of the developers behind [tag:react-router] (and some other libraries too). Pretty much also what @cheersjosh said. It must happen from the server too. – Chris Feb 15 '17 at 08:18
  • Ok, thanks. I'm not doing server-side rendering though, and was hoping there might be a quick solution like the one I tried. – paqash Feb 15 '17 at 09:09

1 Answers1

0

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>
Chilaxathor
  • 626
  • 1
  • 9
  • 10