Published: February 24 2023

React Router v6 - Catch All (Default) Redirect in React

Tutorial built with React 18.2 and React Router 6.8.1

This is a super quick post to show how to create a catch all (default) redirect to the home page (/) in a React app using React Router v6. The redirect runs when a request is made to a route that doesn't exist in the React app.

The way to do it is with a React Router Route component that matches all (*) routes and renders a Navigate element that redirects to the home route ("/") like this: <Route path="*" element={<Navigate to="/" />} />.

Example React Component with Catch All Redirect

Below is an example React component that uses React Router v6, it has a few page routes configured and a default catch all redirect to the home page.

import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';

import { Home, About, Services, Contact } from 'pages';

export { App };

function App() {
    return (
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<Home />} />
                <Route path="about" element={<About />} />
                <Route path="services" element={<Services />} />
                <Route path="contact" element={<Contact />} />

                {/* default redirect to home page */}
                <Route path="*" element={<Navigate to="/" />} />
            </Routes>
        </BrowserRouter>
    );
}

 


Need Some React Help?

Search fiverr for freelance React developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by