Conditional Rendering
In one line
Conditional rendering means showing different JSX based on a condition — using if statements, ternary operators, or logical &&.
In simple words
Conditional rendering is how you show or hide parts of the UI based on state or props. React gives you several patterns:
- Ternary operator:
{isLoggedIn ? <Dashboard /> : <Login />}— show one of two options. - Logical &&:
{hasError && <ErrorMessage />}— show something or nothing. - Early return: extract into a variable with an
ifstatement before the return. - Switch statement: for multiple mutually exclusive options.
All of these work because JSX is JavaScript — you can use any JS expression inside curly braces. The key rule is that every branch must return valid JSX (or null to render nothing).
Example
jsx
function Greeting({ isLoggedIn, name }) {
return (
<div>
{isLoggedIn ? (
<h1>Welcome back, {name}!</h1>
) : (
<h1>Please sign in.</h1>
)}
</div>
);
}The ternary operator chooses between a welcome message and a sign-in prompt based on isLoggedIn.
Related terms
Related Resources
Related Lessons
- Conditional Rendering
Learn patterns for conditional UI.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.