0
0
Reactframework~5 mins

Ternary operator usage in React - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the ternary operator in React JSX?
It is a short way to write an if-else condition inside JSX using the syntax: condition ? expressionIfTrue : expressionIfFalse.
Click to reveal answer
beginner
How do you use the ternary operator to conditionally render text in React?
You write something like: {isLoggedIn ? 'Welcome back!' : 'Please log in.'} inside JSX to show different text based on isLoggedIn.
Click to reveal answer
intermediate
Can the ternary operator be nested in React JSX?
Yes, you can nest ternary operators but it can make code hard to read. It's better to keep conditions simple or use helper functions.
Click to reveal answer
intermediate
Why is the ternary operator preferred over if-else statements inside JSX?
Because JSX expects expressions, not statements. The ternary operator is an expression and fits naturally inside JSX curly braces.
Click to reveal answer
beginner
Show a simple React functional component using the ternary operator to display 'ON' or 'OFF' based on a boolean prop.
function Switch({ isOn }) {
  return <div>{isOn ? 'ON' : 'OFF'}</div>;
}
Click to reveal answer
What does the ternary operator syntax look like in React JSX?
Aif (condition) { trueExpression } else { falseExpression }
Bcondition ? trueExpression : falseExpression
Ccondition && trueExpression
Dswitch(condition) { case true: trueExpression; }
Which of these is a valid use of the ternary operator in JSX?
A{isActive ? <p>Active</p> : <p>Inactive</p>}
Bif (isActive) { <p>Active</p> } else { <p>Inactive</p> }
C{if isActive then <p>Active</p> else <p>Inactive</p>}
D<p>{if isActive then 'Active' else 'Inactive'}</p>
What happens if the condition in a ternary operator is false?
ABoth expressions run
BThe expression before the question mark (?) runs
CThe expression after the colon (:) runs
DNothing runs
Is it good practice to nest many ternary operators in JSX?
AOnly if you use React class components
BYes, it is recommended
COnly if you use more than three conditions
DNo, it makes code hard to read
Which of these is NOT a reason to use the ternary operator in React JSX?
ATo replace all JavaScript if statements
BTo conditionally render elements
CBecause JSX only accepts expressions
DTo write concise conditional code
Explain how the ternary operator works in React JSX and why it is useful.
Think about how you show different things on the screen based on a condition.
You got /4 concepts.
    Describe a simple example of using the ternary operator in a React functional component.
    Imagine a switch that shows ON or OFF depending on a true or false value.
    You got /4 concepts.