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>
);
}
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.