Show or hide elements in React using if statements, ternaries, logical operators, and switch patterns.
function UserInfo({ user }) {
if (!user) return <p>Loading...</p>;
return <div>{user.name}</div>;
}<div>{user ? user.name : "Guest"}</div><div>{user ? (user.isAdmin ? "Admin" : "User") : "Guest"}</div>&& to render JSX only when a condition is true.<div>{user && <p>Hello, {user.name}!</p>}</div>&& with 0 or empty strings.{count > 0 && <p>{count} items</p>}function Status({ status }) {
switch (status) {
case "loading":
return <p>Loading...</p>;
case "success":
return <p>Done!</p>;
case "error":
return <p>Error occurred</p>;
default:
return null;
}
}function IfAdmin({ children, user }) {
return user?.isAdmin ? children : null;
}
<IfAdmin user={user}>
<AdminPanel />
</IfAdmin>Use a ternary inside JSX when you need to choose between two inline values or elements. Reach for an if statement when the logic is complex or you're returning entirely different component trees, since it keeps your JSX cleaner and the logic easier to test.
The && operator short-circuits to the left operand when it's falsy, and React renders the number 0. Convert the left side to a boolean first: use !!count &&
Use a switch statement or extract the logic into a helper function that returns JSX. This keeps your render method readable and makes each branch independently testable, especially when you have more than two possible states.
No, if statements are not expressions and can't appear inside JSX curly braces. Move the conditional logic above the return statement or wrap it in an immediately invoked function expression, though the former is almost always cleaner.
Use a ternary expression in the className prop: className={isActive ? 'active' : 'inactive'}. For multiple conditional classes, the classnames or clsx library keeps the logic readable without manual string concatenation.