Loading lessons...
Conditional Rendering
Conditional Rendering
Conditional rendering in React works the same way conditions work in JavaScript. You can dynamically render different JSX blocks depending on component props or state values.
Approach 1: if / else Statements
Standard if statements are useful when you want to return entirely different JSX trees based on a condition.
function UserStatus({ isLoggedIn, user }) {
if (isLoggedIn) {
return <h1>Welcome back, {user.name}!</h1>;
}
return <h1>Please log in to continue.</h1>;
}
Approach 2: Ternary Operator (condition ? true : false)
Ternary operators allow inline conditional rendering directly inside JSX expressions.
function LoginButton({ isLoggedIn }) {
return (
<button className="btn">
{isLoggedIn ? "Log Out" : "Log In"}
</button>
);
}
Approach 3: Logical AND Operator (&&)
Use the && operator when you want to render a JSX block only when a condition is true, and render nothing when false.
function NotificationBadge({ unreadCount }) {
return (
<div className="inbox">
<span>Inbox</span>
{unreadCount > 0 && (
<span className="badge">{unreadCount}</span>
)}
</div>
);
}
Be careful when using numbers with &&! If the left side evaluates to 0, JavaScript renders 0 on screen instead of nothing. Always use booleans: unreadCount > 0 && <Badge />.
Approach 4: Preventing Rendering with null
If a component should render nothing at all under a specific condition, return null.
function Banner({ isVisible }) {
if (!isVisible) {
return null; // Renders nothing in the DOM
}
return <div className="banner">Special Sale Today!</div>;
}
Summary & TL;DR
- Use
if / elsestatements for returning completely different JSX elements. - Use ternaries (
cond ? <A /> : <B />) for inline binary decisions inside JSX. - Use logical AND (
cond && <A />) for conditionally including an element when true. - Return
nullfrom a component to hide it from DOM output completely.