I have a user route with two children.
I used path="*" in the case where the url does not match with a user so that it then returns UserNotFoundPage.
The problem is, while it does give me UserNotFoundPage when the url is .../user/someIncorrectUsername , it gives me an empty page if I only enter .../user/ or .../user . While I would have expected it to get me to the UserNotFoundPage.
How can I get this behavior ?
Here is my code:
<Router>
<Routes>
{/* PUBLIC */}
<Route path="*" element={<Navigate replace to="/welcome"/>}/>
<Route path="/welcome" element={<HomePage/>}/>
<Route path="/dashboard" element={<DashboardPage/>}/>
{/* RESTRICTED */}
<Route path="/login" element={<LoginPage/>}/>
{/* PRIVATE */}
<Route path="/user" element={<Users/>}>
<Route path="*" element={<UserNotFoundPage/>}/>
<Route path="username" element={<UserProfilePage/>}>
</Route>
</Route>
</Routes>
</Router>
function useAuth() {
return true;
}
function HomePage() {
return (
<div>
<h1>HOME PAGE</h1>
</div>
)
}
function UserNotFoundPage() {
return (
<div>
<p>User not found</p>
</div>
)
}
function Users() {
const auth = useAuth();
return auth ? <Outlet/> : <Navigate to="/login"/>;
}
function UserProfilePage() {
return (
<div>
<h4>USER PROFILE PAGE</h4>
</div>
)
}
function LoginPage() {
return (
<div>
<h2>
Login page
</h2>
</div>
)
}
The issue here is that abstractly "/user" also represents a route path that can be matched and rendered, via the Outlet, but there is no content to render on an exactly matched "/user" path.
An
<Outlet>should be used in parent route elements to render their child route elements. This allows nested UI to show up when child routes are rendered. If the parent route matched exactly, it will render a child index route or nothing if there is no index route.
You can specify the UserNotFoundPage route to be the route that matches and renders on "/user" as well as on any non-matched "/user/*" path by specifying it to be the index route.
<Route path="/user" element={<Users/>}>
<Route index path="*" element={<UserNotFoundPage/>}/>
<Route path="username" element={<UserProfilePage/>}>
</Route>