EasyReact Router📖 Theory Question

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

  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
  }
}
💡 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.

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint