Handling NotFound Routes
In a React Router application, it is common to provide a custom 404 page or handle routes that do not match any defined routes. This ensures that users are presented with a meaningful user interface even when they navigate to invalid or non-existent routes.
To handle NotFound routes, we can define a special Route
component with the path
set to '*'
as the last route in our route configuration. This Route will be matched only when none of the other routes match. Inside this component, we can render a custom 404 page or redirect the user to a different route.
Here's an example of how we can handle NotFound routes:
SNIPPET
1import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
2
3const NotFound = () => {
4 return (
5 <div>
6 <h1>404 - Page not found</h1>
7 <p>The page you are looking for does not exist.</p>
8 </div>
9 );
10};
11
12const App = () => {
13 return (
14 <Router>
15 <Switch>
16 <Route exact path='/' component={Home} />
17 <Route path='/about' component={About} />
18 <Route path='/contact' component={Contact} />
19 <Route component={NotFound} />
20 </Switch>
21 </Router>
22 );
23};