The Ternary Operator for If-Else in JSX
What you'll learn: How to render one of two different elements based on a condition using the ternary operator in JSX.
The Core Idea
You've already learned how to conditionally show or hide something with &&. But what if you need to choose between two different pieces of JSX? Maybe display "Hello!" when logged in, but "Please sign in" when logged out?
This is where the ternary operator shines: condition ? trueJSX : falseJSX
Think of it like a fork in the road: if the condition is true, React takes the left path (before the :), otherwise it takes the right path (after the :).
The Syntax
{isLoggedIn ? <WelcomeMessage /> : <LoginPrompt />}
If isLoggedIn evaluates to true, React renders <WelcomeMessage />. If false, it renders <LoginPrompt /> instead.
When to Use It
The ternary operator is perfect when you have exactly two options:
{hasMessages ? <MessageCount count={5} /> : <p>No messages</p>}
{age >= 18 ? "Adult" : "Minor"}
{score > 50 ? <Badge color="green" /> : <Badge color="red" />}
Unlike &&, which only controls whether something appears, the ternary always renders something—the condition just determines which thing.
Ternary vs &&
- Use
&&when: Show X or nothing - Use ternary when: Show X or Y
Both accept the same truthy/falsy rules you learned before, so the same cautions apply (watch out for 0!).
Key Takeaway: Use condition ? trueJSX : falseJSX when you need to choose between two different elements based on a boolean expression—it's the if-else statement of JSX.