6

I'm building a website with React and using React-Router, I'd like to render a 404 page when a url is visited by the user that doesn't exist.

Some urls are dynamic, say,

www.site.com/user/(username)

How do I render a 404 page with react-router if the user with a particular username doesnt exist? Do I have to manually write code in the component itself during the API calls to check if user exists and then redirect the user to the 404 component?

I'm looking for the best way to redirect the user to a not found page. Looking for ideas on how to do it best.

1
  • 1
    Unfortunately the only way is to have the condition in the component matching user/(username). And then either let the component render an error or you can use <Redirect ... /> to redirect to a error page as described by @canaan seaton Commented Aug 15, 2017 at 14:25

3 Answers 3

2

Use Switch then Redirect

https://reacttraining.com/react-router/web/example/no-match

https://reacttraining.com/react-router/web/api/Redirect

Valid URL no redirect: /user/valid_username

404 URL redirects: /user/invalid_username

import React, { Component } from 'react'
import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom'

class App extends Component {
  render() {
    return (
      <Router>
        <div>
          <Switch>
            <Route path="/user/:username" component={Child} />
            <Route path="/404" component={NoMatch} />
            <Route component={NoMatch} />
          </Switch>
        </div>
      </Router>
    )
  }
}

function Child({ match }) {
  // perform some username check
  if (match.params.username !== 'valid_username') {
    return (
      <div>
        <Redirect to="/404" />
      </div>
    )
  }
  return (
    <div className="App">
      <h3>ID: {match.params.username}</h3>
    </div>
  )
}

function NoMatch({ location }) {
  return (
    <div>
      <h3>
        404 - No match for <code>{location.pathname}</code>
      </h3>
    </div>
  )
}

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

1 Comment

This doesnt actually tell the browser 'httpcode 404' it tells the browser '200 ok'. when updating the website with new files (for example chunk.js files) and a user going to the website for the firsttime they will get the nomatch page as .js content.
1

You could check to see if this.props.match.username exists. If it does then render as normal if it doesnt then use React-Router Redirect Component to redirect to a 404 component. If you have multiple paths that require this functionality then you may consider making a HOC for this purpose.

Comments

0

You can resolve this issue by rendering a Route with a path of *, and React Router will make sure to only render the element if none of the other Routes match.

<Routes>
  <Route path="*" element={<NotFound />} />
  <Route path="/" element={<Home />} />
  <Route path="/about" element={<About />} />
</Routes>

For more: https://ui.dev/react-router-handling-404-pages

Comments

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.