How do you implement protected routes in React Router?
Hint
Wrapper component that checks auth state and redirects — compose with Outlet for nested protection
Full Answer
// ─── 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 <Navigate to="/login" state={{ from: location }} replace />;
}
return children;
}
// Usage
<Route path="/dashboard" element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
} />
// ─── Option 2: Layout route (cleaner for many protected routes) ───────────────
function RequireAuth() {
const { user } = useAuth();
const location = useLocation();
if (!user) {
return <Navigate to="/login" state={{ from: location }} replace />;
}
return <Outlet />; // render the matched child
}
// Wrap all protected routes under one parent
<Routes>
<Route path="/login" element={<Login />} />
<Route element={<RequireAuth />}> {/* no path — just a guard */}
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/settings" element={<Settings />} />
<Route path="/profile" element={<Profile />} />
</Route>
</Routes>
// 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
}
}
💡 Always use replace when redirecting after login — so the user's back button goes to where they originally wanted to go, not to a login loop.
More React Router Questions
Practice this in a timed sprint
5 free questions, no signup required