Published: September 08 2021

React - Catch All (Default) Redirect with React Router 5

Tutorial built with React 17.0.2 and React Router 5.3.0

This is a super quick post to show how to create a catch all (default) redirect to the home page (/) in a React app that uses React Router v5. 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 Redirect component that redirects from all (*) routes and redirects to the home (/) route like this: <Redirect from="*" to="/" />.

Example React App Component with Catch All Redirect

Below is an example React component with a few page routes configured and a default catch all redirect to the home page.

import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';

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

export { App };

function App() {
    return (
        <Router>
            <Switch>
                <Route exact path="/" component={Home} />
                <Route path="/about" component={About} />
                <Route path="/services" component={Services} />
                <Route path="/contact" component={Contact} />

                {/* default redirect to home page */}
                <Redirect from="*" to="/" />
            </Switch>
        </Router>
    );
}

 


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