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?

3
  • 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. knowbody.github.io/react-router-docs/api/match.html Commented Feb 15, 2017 at 1:20
  • 1
    Check out the other response in that same question you linked. stackoverflow.com/a/36075450/2030321 Taion is actually one of the developers behind react-router (and some other libraries too). Pretty much also what @cheersjosh said. It must happen from the server too. Commented Feb 15, 2017 at 8: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. Commented Feb 15, 2017 at 9:09

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Nick, it's been a long time coming :)

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.