Here's the best way to implement a 404 page using React Router:
1. Set Up React Router
First, ensure you have React Router installed in your project:
npm install react-router-dom
2. Create a 404 Component
Create a dedicated component for the 404 page. For example:
import React from 'react';
const NotFound = () => {
return (
<div>
<h1>404 - Page Not Found</h1>
<p>The page you are looking for does not exist.</p>
</div>
);
};
export default NotFound;
3. Configure Routes in React Router
Use a Route with a path="*" to catch all undefined routes and render the 404 component. This should be placed at the end of your route configuration to ensure it only matches when no other routes do.
Here’s an example of how to set this up:
// src/App.js
import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import NotFound from './components/NotFound';
const App = () => {
return (
<Router>
<Routes>
{/* Define your routes */}
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
{/* Catch-all route for 404 */}
<Route path="*" element={<NotFound />} />
</Routes>
</Router>
);
};
export default App;