Blog>
Snippets

Handling 404 Errors with React Router

Show how to handle non-existent routes in a React application by setting up a catch-all route with React Router that displays a custom 404 page.
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import NotFound from './components/NotFound';
First, we import the necessary components from react-router-dom and our page components. 'NotFound' is our custom 404 component.
function App() {
  return (
    <Router>
      <Switch>
        <Route exact path='/' component={Home} />
        <Route path='/about' component={About} />
        <Route component={NotFound} />
      </Switch>
    </Router>
  );
}
Within our App component, we set up the Router and the Switch. The Switch goes through each Route to find a match. The Route without a path acts as a catch-all for undefined routes, rendering our NotFound component for any route that doesn't match the ones defined.