Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly render a 404 page in React with React-Router?

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.

like image 354
kotAPI Avatar asked Oct 18 '22 07:10

kotAPI


1 Answers

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
like image 167
Simon Hutchison Avatar answered Oct 21 '22 05:10

Simon Hutchison