Lesson 20 of 3067%
(Progress persistence is disabled until Phase 9)
React
Beginner
Conditional Rendering
Rendering different UI based on state.
You can use standard JavaScript logic (if statements, ternary operators, logical AND) to conditionally render JSX.
Logical AND (&&)
Useful if you want to render something only if a condition is true.
function Dashboard({ unreadMessages }) {
return (
<div>
<h1>Dashboard</h1>
{unreadMessages > 0 && <p>You have new messages!</p>}
</div>
);
}
Ternary Operator (? :)
Useful for choosing between two options.
function LoginButton({ isLoggedIn }) {
return isLoggedIn ? <button>Logout</button> : <button>Login</button>;
}
Try It Yourself