As stated in React Router 6's documentation, the simples way to add a global 404 page is to use a wildcard *
route i.e.:
function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="dashboard" element={<Dashboard />} />
<Route path="*" element={<NotFound />} />
</Routes>
);
}
But, how should we go in a more complex scenario with several descendant routes with their own layout and route definitions like this:
function Feature1 () {
return (
<FeatureLayout>
<Routes>
<Route path="/" element={<Home />} />
<Route path="foo" element={<Foo />} />
<Route path="bar" element={<Bar />} />
</Routes>
</FeatureLayout>
);
}
function Feature2 () {
return (
<FeatureLayout>
<Routes>
<Route path="/" element={<Home />} />
<Route path="foo" element={<Foo />} />
<Route path="bar" element={<Bar />} />
</Routes>
</FeatureLayout>
);
}
function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="dashboard" element={<Dashboard />} />
<Route path="feature1/*" element={<Feature1 />} />
<Route path="feature2/*" element={<Feature2 />} />
<Route path="*" element={<NotFound />} />
</Routes>
);
}
In this case, our global *
route is not going to be reached if we fall under the feature1/*
, and feature2/*
descendant routes, because the routing will go on and be handled by the underlying components. Descendant routes can go several levels deep because its a really convenient way to organize routes.
So my question is, how to have a single standard 404 page with its own layout that gets fired if no routes or descendant routes match the current path?
Important: Please do not suggest explicit /404
page, the solution should keep the URL without redirecting to /404
path.