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>
);
}
Subscribe or Follow Me For Updates
Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.
- Subscribe on YouTube at https://www.youtube.com/JasonWatmore
- Follow me on Twitter at https://twitter.com/jason_watmore
- Follow me on Facebook at https://www.facebook.com/JasonWatmoreBlog
- Follow me on GitHub at https://github.com/cornflourblue
- Feed formats available: RSS, Atom, JSON
Other than coding...
I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.
- Subscribe on YouTube at https://www.youtube.com/TinaAndJason
- Follow us on Instagram at https://www.instagram.com/tinaandjason
- Follow us on Facebook at https://www.facebook.com/TinaAndJasonVlog
- Visit our website at https://tinaandjason.com.au
Need Some React Help?
Search fiverr to find help quickly from experienced React developers.