Careeroza
withAuth Example
Protect Components
Example
import { useState } from 'react';
function withAuth(Component) {
return function WithAuth({ user, ...props }) {
if (!user) return <p>🔒 Please log in to see this.</p>;
return <Component user={user} {...props} />;
};
}
function Dashboard({ user }) {
return <h3>Welcome to your dashboard, {user.name}</h3>;
}
const ProtectedDashboard = withAuth(Dashboard);
export default function App() {
const [user, setUser] = useState(null);
return (
<div>
<button onClick={() => setUser(user ? null : { name: 'Asha' })}>{user ? 'Logout' : 'Login'}</button>
<ProtectedDashboard user={user} />
</div>
);
}Result