Hint
Wrapper component that checks auth state and redirects — compose with Outlet for nested protection
// ─── Option 1: Wrapper component ─────────────────────────────────────────────
function ProtectedRoute({ children }) {
const { user } = useAuth();
const location = useLocation();
if (!user) {
// Redirect to login, save the page they tried to visit
return ;
}
return children;
}
// Usage
} />
// ─── Option 2: Layout route (cleaner for many protected routes) ───────────────
function RequireAuth() {
const { user } = useAuth();
const location = useLocation();
if (!user) {
return ;
}
return ; // render the matched child
}
// Wrap all protected routes under one parent
} />
}> {/* no path — just a guard */}
} />
} />
} />
// After login — redirect to original destination
function Login() {
const navigate = useNavigate();
const location = useLocation();
const from = location.state?.from?.pathname || '/dashboard';
async function handleLogin(creds) {
await login(creds);
navigate(from, { replace: true }); // replace so back button works
}
}