How to conditionally render elements in React
· Category: React
Short answer
React supports conditional rendering via ternary operators, logical AND (&&), if-statements outside JSX, and early returns in components.
Steps
- Use early returns for loading or error states before the main JSX.
- Use ternary operators for choosing between two elements inside JSX.
- Use
&&for rendering something only when a condition is true. - Extract complex conditions into a variable or helper function for readability.
Example
function Banner({ isLoggedIn, user }) {
if (!user) return <p>Loading...</p>;
return (
<div>
{isLoggedIn ? (
<h1>Welcome back, {user.name}</h1>
) : (
<h1>Please sign in</h1>
)}
{user.isAdmin && <AdminPanel />}
</div>
);
}
Common issues
- Beware of falsy values like
0with&&;count && <List />will render0if count is zero. Usecount > 0 && <List />instead.