React Icon Get 67% off the React Master Bundle!

See the bundle then add to cart and your discount is applied.

0 days
00 hours
00 mins
00 secs

Redirect Default or 404 Routes with React Router

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:

    <Route path="users" element={<Users />} />
    <Route path="posts" element={<Posts />} />

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):

    <Route path="users" element={<Users />} />
    <Route path="posts" element={<Posts />} />
    <Route path="" element={<Navigate to="/users" />} />

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.

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>{}</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!

Related blogs 🚀

Free eBooks:

JavaScript Array Methods eBook Cover

Ready to go beyond ForEach? Get confident with advanced methods - Reduce, Find, Filter, Every, Some and Map.

NestJS Build a RESTful CRUD API eBook Cover

Build your first NestJS app. With the CLI you'll learn the basics of real-world NestJS development.