Page redirection in the new React router v6 can be tricky.
Let's say you have the following routes
<Router>
<Routes>
<Route path="home" element={<Home />} />
<Route path="profile" element={<Profile />} />
</Routes>
</Router>
However, that means that if we navigate to /home
or /todo
, none of the routes will be rendered.
This is a classic use case example for a 404 page.
Adding a 404 page
<Router>
<Routes>
<Route path="home" element={<Home />} />
<Route path="profile" element={<Profile />} />
<Route path="*" element={<Page404 />} />
</Routes>
</Router>
In this example react router will fallback to the 404 page if the user attemps to enter an invalid url.
The "*" will catch all the paths that have not been caught by previous routes.
The 404 page should thus be the last route to be rendered.
Adding a page redirect
We can improve the code further by adding a redirect for the default home directory.
This way the user can access the home page by either navigating to /home or to / (which would redirect him to home).
<Router>
<Routes>
<Route path="home" element={<Home />} />
<Route path="profile" element={<Profile />} />
<Route index element={<Navigate to="/home" />} />
<Route path="*" element={<Page404 />} />
</Routes>
</Router>
If you liked this tutorial consider visiting my website Code with Vlad where I provide high quality programming courses.
Top comments (0)