React Router > React Router 404 Route
React Router 404 Route
To implement a 404 Not Found route, we can use the wildcard *
to catch any path. Because the paths are matched in order, if any of the previous paths do not match the current location, this NotFound element will be rendered.
Try clicking on the "NoteFoundRoute" in the NavBar.
At this point, our routes look like this:
<BrowserRouter>
<Routes>
<Route element={<Layout />}>
<Route index element={<Home />} />
<Route path="missions" element={<Missions />} />
<Route path="logs" element={<Logs />} />
<Route path="account" element={<Account />} />
<Route path="*" element={<NotFound />} />
</Route>
</Routes>
</BrowserRouter>
Next we'll improve the design of the Home page.
import styled from "styled-components"; import { BrowserRouter, Routes, Route, Outlet, Link } from "react-router-dom"; import NavBar from "./Components/NavBar"; const LayoutContainer = styled.div` margin: auto; max-width: 800px; padding: 20px; `; function Layout() { return ( <LayoutContainer> <NavBar /> <Outlet /> </LayoutContainer> ); } function Home() { return <div> Home </div>; } function Missions() { return <div> Missions </div>; } function Logs() { return <div> Logs </div>; } function Account() { return <div> Account </div>; } function NotFound() { return <div> Not found </div>; } function App() { return ( <BrowserRouter> <Routes> <Route element={<Layout />}> <Route index element={<Home />} /> <Route path="missions" element={<Missions />} /> <Route path="logs" element={<Logs />} /> <Route path="account" element={<Account />} /> <Route path="*" element={<NotFound />} /> </Route> </Routes> </BrowserRouter> ); } export default App;