In a React Router application, it is important to handle errors such as route not found errors. When a user navigates to a route that does not exist, you can display a custom error page to provide a better user experience.
One way to handle route not found errors is by defining a Route
component without a path
prop at the end of your Switch
component. This component will act as a catch-all for any routes that do not match the defined paths.
Here's an example of how to handle 404 errors in a React Router application:
1// Handling 404 Errors
2
3const NotFound = () => {
4 return (
5 <div>
6 <h1>404 Not Found</h1>
7 <p>The page you are looking for does not exist.</p>
8 </div>
9 );
10};
11
12function App() {
13 return (
14 <div>
15 <Router>
16 <Switch>
17 <Route exact path='/' component={Home} />
18 <Route path='/about' component={About} />
19 <Route path='/contact' component={Contact} />
20 <Route component={NotFound} />
21 </Switch>
22 </Router>
23 </div>
24 );
25}
In this example, the NotFound
component is rendered when none of the previous routes match. It displays a 404 Not Found error message to inform the user that the page they are looking for does not exist.
By handling route not found errors, you can provide a better user experience by displaying a custom error page instead of the default browser error page. This helps to ensure that users can easily navigate your application even when they enter an incorrect URL.
xxxxxxxxxx
// Handling 404 Errors
const NotFound = () => {
return (
<div>
<h1>404 Not Found</h1>
<p>The page you are looking for does not exist.</p>
</div>
);
};
function App() {
return (
<div>
<Router>
<Switch>
<Route exact path='/' component={Home} />
<Route path='/about' component={About} />
<Route path='/contact' component={Contact} />
<Route component={NotFound} />
</Switch>
</Router>
</div>
);
}