How to Use Ternary Operator in React: Simple Conditional Rendering
In React, use the
ternary operator inside JSX to conditionally render elements by writing condition ? trueExpression : falseExpression. This lets you show different UI parts based on a condition in a concise way.Syntax
The ternary operator in React JSX follows this pattern:
condition: a boolean expression to check.trueExpression: JSX or value to render ifconditionis true.falseExpression: JSX or value to render ifconditionis false.
This operator is placed inside curly braces {} in JSX to embed JavaScript expressions.
jsx
return ( <div> {condition ? <p>Show if true</p> : <p>Show if false</p>} </div> );
Output
<div>Show if true or Show if false depending on condition</div>
Example
This example shows a React component that uses the ternary operator to display a greeting based on a isLoggedIn boolean state.
jsx
import React, { useState } from 'react'; function Greeting() { const [isLoggedIn, setIsLoggedIn] = useState(false); return ( <div> {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>} <button onClick={() => setIsLoggedIn(!isLoggedIn)}> {isLoggedIn ? 'Logout' : 'Login'} </button> </div> ); } export default Greeting;
Output
When isLoggedIn is false: "Please sign in." and button "Login"; when true: "Welcome back!" and button "Logout"
Common Pitfalls
Common mistakes when using the ternary operator in React include:
- Forgetting to wrap the ternary expression in curly braces
{}inside JSX. - Using the ternary operator without an
elsepart, which can cause syntax errors. - Writing complex nested ternaries that reduce readability.
Use parentheses to group complex expressions for clarity.
jsx
/* Wrong: Missing curly braces */ // return <div>isLoggedIn ? <p>Yes</p> : <p>No</p></div>; /* Right: With curly braces */ // return <div>{isLoggedIn ? <p>Yes</p> : <p>No</p>}</div>;
Quick Reference
Tips for using the ternary operator in React:
- Always wrap the ternary expression in
{}inside JSX. - Use it for simple conditional rendering to keep code clean.
- For multiple conditions, consider using
ifstatements or helper functions for readability. - Remember the syntax:
condition ? truePart : falsePart.
Key Takeaways
Use the ternary operator inside JSX with curly braces for conditional rendering.
The syntax is: condition ? trueExpression : falseExpression.
Avoid complex nested ternaries to keep code readable.
Always include both true and false parts to prevent syntax errors.
For multiple conditions, prefer clearer alternatives like if statements.