React Router provides the <Route>
element for us to easily declare routes for rendering when a particular path matches in the URL. But let’s say your path doesn’t match, how are you going to handle it? Just let it error? No!
✨ Written for React Router v6, check out my brand new React Router v6 course to fully master it.
And what about handling default routes, where we have the base path ''
? If you wish, you can redirect your users to a new route of your choice as soon as they hit your application’s root or a route that’s not found. Here’s how!
Let’s take a basic <Router>
config that will render either components based on whether the URL is /users
or /posts
:
<Router>
<Routes>
<Route path="users" element={<Users />} />
<Route path="posts" element={<Posts />} />
</Routes>
</Router>
But you’ll notice that when you visit the demo below, that neither URL are being activated (which is what we expect as no default route is supplied):
To redirect and navigate to one of our chosen routes, we’ll import the <Navigate>
component from React Router. From there, we can declare below our route configuration the case for empty routes (it’s important to add this at the end, so it’s the last route not matched):
<Router>
<Routes>
<Route path="users" element={<Users />} />
<Route path="posts" element={<Posts />} />
<Route path="" element={<Navigate to="/users" />} />
</Routes>
</Router>
So now we’ve supplied a path
for an empty route, when our React application bootstraps we’ll now navigate from our default route to a route of our choice. You can see this working below as the “Users” link will show active:
Nice and clean! And that’s pretty much all there is to it for using the <Navigate>
component to redirect to a new route.
Free eBook
Directives, simple right? Wrong! On the outside they look simple, but even skilled Angular devs haven’t grasped every concept in this eBook.
- Observables and Async Pipe
- Identity Checking and Performance
- Web Components <ng-template> syntax
- <ng-container> and Observable Composition
- Advanced Rendering Patterns
- Setters and Getters for Styles and Class Bindings
You can also use this component directly inside your other components too to handle redirects instead of the React Router hooks API, depending on your flavour of imperative and declarative:
const Users = ({ user }) => {
if (!user) {
return <Navigate to="/users" />;
}
return <div>{user.name}</div>;
};
You could then opt for using the React Router hooks API via the navigate()
function for handling redirects on something like a button click callback.
💯 If you are serious about your React skills, your next step is to take a look at my React courses where you’ll learn React, React Router, Styling and CSS practices, advanced concepts and APIs as well as server-side rendering and much more.
Happy redirecting!