How to Creating a custom 404 Page with React Routers V6?

Naveen DA
2 min readDec 31, 2022

--

React Router is a popular JavaScript library for building single-page applications with React. It provides a set of components and functions that enable you to declaratively define your application’s routing and navigation.

In this blog post, we will look at how to create a custom 404 page with React Router v6. A 404 page is a page that is displayed when a user tries to access a URL that does not exist on your website. By default, React Router will display a simple “404 — Page Not Found” message when a user tries to access a URL that does not match any of the routes in your application. However, you can customise this message by creating a custom 404 page using the NotFound component provided by the library.

const NotFound = () => {
return (
<>
<h1>404 - Page Not Found</h1>
<p>Sorry, the page you are looking for could not be found.</p>
</>
);
};

const App = () => {
return (
<Router>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/contact">
<Contact />
</Route>
{/* This is where magic happens */}
<Route path="*" element={<NotFound />} />
</Switch>
</Router>
);
};

“The NotFound component should be placed at the bottom of the Switch component in a React Router application so that it will only be rendered if none of the other routes in the Switch component match the current URL. This allows the NotFound component to act as a catch-all or wildcard route that handles URLs that do not match any of the defined routes in the application."

Happy coding👩‍💻👨‍💻

--

--

Naveen DA
Naveen DA

No responses yet