How to Create a 404 Page in React js Using React Router Dom V6
In this lesson, we will see how to create a 404 page in react js using react-router-dom v6, so let's see how we can do that.
Create PageNotFound component
First, let's create a PageNotFound component and add the code below inside.
import React from 'react';
import { Link } from 'react-router-dom';
export default function PageNotFound() {
return (
<div className="container">
<div className="row my-5">
<div className="col-md-6 mx-auto">
<div className="card">
<div className="card-body">
<h3>404 Page Not Found</h3>
<Link className="my-3" to="/">
Back Home
</Link>
</div>
</div>
</div>
</div>
</div>
)
}
Update the routes file
Next, let's update our routes and add the 404 not found route.
import React from 'react';
import { Routes, Route } from "react-router-dom";
import Header from "./components/Header";
import Home from "./components/Home";
import Cart from "./components/Cart";
import PageNotFound from './components/PageNotFound';
function App() {
return (
<div className="container">
<Header/>
<Routes>
<Route exact path="/" element={<Home />} />
<Route exact path="/cart" element={<Cart />} />
<Route exact path="*" element={<PageNotFound />} />
</Routes>
</div>
);
}
export default App;