Below in the App.js file , the routes component wraps part of the website , but i needed the NotFound component to be rendered for the whole page if a wrong url was entered , please advice on how this can be done in this case , i appreciate your feedback
const App = () => {
return (
<Box>
<CssBaseline />
<Navbar />
<Routes>
<Route path="/" element={<Navigate to="/home" />} />
<Route path="/home" element={<Home />} />
<Route path="/tours" element={<Tours />} />
<Route path="/music" element={<Music />} />
<Route path="/contact" element={<ContactUs />} />
</Routes>
<Testimonials />
<Footer />
</Box>
);
};
CodePudding user response:
You can simply use a wildcard path "*"
after all valid routes. In this way it will 1st try to match the current user's path with the path provided inside <Route/>
and if the path matches the existing route it will render that route's component. And when it will not match with your existing path then it will render the wildcard route
and inside the wildcard route, you can render the 404 Not Found page. For example:
const App = () => {
return (
<Box>
<CssBaseline />
<Navbar />
<Routes>
<Route path="/" element={<Navigate to="/home" />} />
<Route path="/home" element={<Home />} />
<Route path="/tours" element={<Tours />} />
<Route path="/music" element={<Music />} />
<Route path="/contact" element={<ContactUs />} />
<Route path="*" element={<NotFoundComponent/>} />
</Routes>
<Testimonials />
<Footer />
</Box>
);
};
Note: The <Route path="*"/>
should be placed after all existing routes or else your react app will render a 404
page every time