Ternary operator
- React course
- Beginner
- Lesson 23/84
- 4 min
Learn to write short conditional rendering with condition ? a : b.
Ternary operator
The ternary operator takes the form condition ? trueValue : falseValue. It's used inside JSX with curly braces: { 'count > 0 ? <Full /> : <Empty />' }.
Ternary is the shortest way to choose between two options. It can nest, but limiting nesting is good practice for readability.
Because it returns a value, it can go directly inside curly braces; it doesn't need an extra line like an if statement.
Ternary vs if
Ternary is an expression: it returns a value and can be used inside curly braces. if is a statement: it returns nothing and can't go inside curly braces.
That's why ternary is preferred for conditional rendering inside JSX. if can only be used in the component body, outside the return.
When two nested conditions are needed, a helper variable or early return may read better than ternary.
Practice Label by stock state
Complete the skeleton. Write a component called StockLabel that takes ({ '{ count }' }) as parameter. If count is greater than 0, return <p>In stock</p>; otherwise <p>Out of stock</p> (with ternary). Don't forget to export.
Starter code
// Write the StockLabel component hereSample solution
function StockLabel({ count }) {
return count > 0 ? <p>In stock</p> : <p>Out of stock</p>;
}
export default StockLabel;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How many values does the ternary return?
- One
- Two Correct answer
- Three
- Zero
Explanation: Ternary returns one of two values.
2 Ternary syntax
Ternary starts with the ____ mark.
Ternary starts with the ? mark.
Explanation: ? is the ternary mark.
3 Match the ternary parts
| Term | Meaning |
|---|---|
condition |
Before the question mark |
? |
Question mark |
trueValue |
First value |
falseValue |
Second value |