The ternary operator helps you choose between two things quickly in your React code. It keeps your code short and easy to read.
Ternary operator usage in React
Introduction
Syntax
React
condition ? expressionIfTrue : expressionIfFalse
The
condition is checked first. If it is true, the code after ? runs.If the condition is false, the code after
: runs instead.Examples
message to 'Welcome back!' if isLoggedIn is true, otherwise to 'Please log in.'React
const message = isLoggedIn ? 'Welcome back!' : 'Please log in.';
isActive is true, otherwise gray.React
<button style={{ color: isActive ? 'green' : 'gray' }}>Click me</button>score is 60 or more, else 'Fail'.React
const status = score >= 60 ? 'Pass' : 'Fail';
Sample Program
This React component shows a message and a button. The message and button text change based on whether the user is logged in. Clicking the button toggles the login state.
React
import React, { useState } from 'react'; export default function LoginMessage() { const [isLoggedIn, setIsLoggedIn] = useState(false); return ( <div> <p>{isLoggedIn ? 'Welcome back!' : 'Please log in.'}</p> <button onClick={() => setIsLoggedIn(!isLoggedIn)}> {isLoggedIn ? 'Logout' : 'Login'} </button> </div> ); }
Important Notes
You can use ternary operators inside JSX to decide what to show.
For simple true/false rendering, you can also use condition && expression but ternary is best when you have two choices.
Summary
The ternary operator is a quick way to choose between two values.
It keeps your React code clean and easy to read.
Use it inside JSX to show different things based on conditions.
Practice
1. What does the ternary operator
condition ? expr1 : expr2 do in React JSX?easy
Solution
Step 1: Understand ternary operator structure
The ternary operator has the formcondition ? expr1 : expr2, which means it evaluates the condition first.Step 2: Evaluate the condition result
If the condition is true, it returnsexpr1; if false, it returnsexpr2.Final Answer:
It choosesexpr1ifconditionis true, otherwiseexpr2. -> Option AQuick Check:
Ternary operator = choose between two values [OK]
Hint: Remember: condition ? trueValue : falseValue [OK]
Common Mistakes:
- Thinking it runs both expressions
- Confusing with logical AND/OR operators
- Using it outside JSX incorrectly
2. Which of the following is the correct syntax to use a ternary operator inside JSX to display
"Yes" if isActive is true, else "No"?easy
Solution
Step 1: Check ternary operator syntax in JSX
The ternary operator must be inside curly braces in JSX and followcondition ? expr1 : expr2format.Step 2: Validate each option
{isActive ? "Yes" : "No"}correctly uses{isActive ? "Yes" : "No"}. Options B, C, and D have syntax errors or incomplete expressions.Final Answer:
{isActive ? "Yes" : "No"} -> Option BQuick Check:
Correct JSX ternary syntax ={isActive ? "Yes" : "No"}[OK]
Hint: Use curly braces and ? : inside JSX [OK]
Common Mistakes:
- Missing colon ':' in ternary
- Using semicolon instead of colon
- Not wrapping expression in curly braces
3. What will this React component render?
If
function Greeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>}
</div>
);
}If
isLoggedIn is false?medium
Solution
Step 1: Understand the ternary condition
The component usesisLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>. IfisLoggedInis false, it chooses the second expression.Step 2: Determine output when
SinceisLoggedInis falseisLoggedInis false, it renders<h1>Please sign in.</h1>inside the div.Final Answer:
<div><h1>Please sign in.</h1></div> -> Option AQuick Check:
False condition shows second expression [OK]
Hint: False condition picks expression after colon ':' [OK]
Common Mistakes:
- Choosing first expression for false condition
- Confusing JSX tags rendering
- Expecting empty div output
4. Identify the error in this JSX snippet:
return (
<div>
{isReady ? <p>Ready</p> : <p>Not ready</p>}
{isReady ? <p>Go!</p> : null}
</div>
);medium
Solution
Step 1: Check each ternary usage
The first ternary is correct with both true and false parts. The second uses{isReady ? <p>Go!</p> : null}which is valid syntax.Step 2: Understand ternary operator requirements
The ternary operator requires both true and false expressions separated by a colon. Here, the else part isnull, which is valid JSX.Final Answer:
No error; code is valid. -> Option DQuick Check:
Ternary needs both ? and : parts, and else can be null [OK]
Hint: Ternary always needs ? and : parts [OK]
Common Mistakes:
- Omitting the else expression
- Confusing ternary with logical AND
- Thinking JSX can't have ternary
5. You want to display a list of user names with a label showing if they are online or offline using ternary inside JSX. Which code correctly implements this?
const users = [
{ name: "Alice", online: true },
{ name: "Bob", online: false }
];
function UserList() {
return (
<ul>
{users.map(user => (
<li key={user.name}>
{user.name} - {user.online ? "Online" : "Offline"}
</li>
))}
</ul>
);
}hard
Solution
Step 1: Analyze the map and ternary usage
The code maps over users and uses a ternary to show "Online" ifuser.onlineis true, else "Offline".Step 2: Check React key and JSX correctness
Each<li>has a unique key fromuser.name, and the ternary is correctly inside JSX curly braces.Final Answer:
Correctly shows each user with "Online" or "Offline" label. -> Option CQuick Check:
Map + ternary inside JSX = correct rendering [OK]
Hint: Use map with ternary inside JSX for conditional labels [OK]
Common Mistakes:
- Forgetting unique key in list items
- Trying to use ternary outside JSX braces
- Assuming ternary can't be used in map
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
