How to Use Ternary Operator in JSX for Conditional Rendering
In JSX, you use the
ternary operator inside curly braces to conditionally render elements: {condition ? trueValue : falseValue}. It works like a simple if-else that chooses what to show based on the condition.Syntax
The ternary operator in JSX follows this pattern:
condition: A JavaScript expression that evaluates totrueorfalse.trueValue: What JSX renders if the condition istrue.falseValue: What JSX renders if the condition isfalse.
Wrap the whole expression in curly braces {} to embed it inside JSX.
jsx
{condition ? trueValue : falseValue}Example
This example shows how to display a greeting message based on a isLoggedIn boolean. It uses the ternary operator to choose between two messages.
jsx
import React from 'react'; export default function Greeting() { const isLoggedIn = true; return ( <div> {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up.</h1>} </div> ); }
Output
<h1>Welcome back!</h1>
Common Pitfalls
Common mistakes when using the ternary operator in JSX include:
- Forgetting to wrap the expression in curly braces
{}, so JSX treats it as plain text. - Not providing the
falseValuepart, which can cause syntax errors. - Using complex logic inside the ternary, making code hard to read; prefer simple conditions or extract logic outside JSX.
jsx
/* Wrong: missing curly braces */ // <div>isLoggedIn ? <h1>Hi</h1> : <h1>Bye</h1></div> /* Right: with curly braces */ // <div>{isLoggedIn ? <h1>Hi</h1> : <h1>Bye</h1>}</div>
Quick Reference
Use this quick guide when writing ternary operators in JSX:
| Part | Description | Example |
|---|---|---|
| condition | Expression that returns true or false | isLoggedIn |
| trueValue | Rendered if condition is true | Welcome back! |
| falseValue | Rendered if condition is false | Please sign up. |
| curly braces | Wrap the whole ternary in JSX | {condition ? trueValue : falseValue} |
Key Takeaways
Always wrap the ternary operator expression in curly braces inside JSX.
Use the ternary operator to choose between two JSX elements based on a condition.
Provide both true and false parts to avoid syntax errors.
Keep ternary expressions simple for better readability.
Ternary operator is a concise alternative to if-else for conditional rendering in React.