Careeroza
Real World Example
Real World: Role-based pages in an admin panel
Some pages are only for admins. A withRole HOC wraps those pages so the check is written once.
function withRole(Component, role) {
return function Guarded(props) {
const { user } = useAuth();
if (!user) return <Navigate to="/login" />;
if (user.role !== role) return <p>Access denied</p>;
return <Component {...props} />;
};
}
const AdminSettings = withRole(SettingsPage, 'admin');
const ManageUsers = withRole(UsersPage, 'admin');