React · Lesson 15 of 120
Conditional Rendering
If, &&, ternary.
Often, part of the page depends on a condition. Show a sale badge only for discounted bikes. Show sold out when stock is zero. JSX has three common ways to do this.
- Show or hide
- Choose between two
- Three patterns
Three ways
An early return shows nothing for hidden bikes. Two ampersands show the sale badge only when there's a discount. A ternary chooses between in stock and sold out. Run it.
App.jsxjsx
function Bike({ model, stock, discount, hidden }) {
if (hidden) return null;
return (
<div className="box">
<b>{model}</b> {discount && <span>🔥 {discount}% off</span>}
<p>{stock > 0 ? "In stock" : "Sold out"}</p>
</div>
);
}
export default function App() {
return (
<>
<Bike model="Trail 500" stock={12} discount={10} />
<Bike model="City 200" stock={0} />
<Bike model="Old 100" stock={3} hidden />
</>
);
}Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Watch out for zero
Two ampersands with a number can print a zero on the page. If count is zero, count and something shows zero. Use count greater than zero, and something, instead.
| key | value |
|---|---|
| if + return null | hide it all |
| cond && <X/> | show or nothing |
| a ? <X/> : <Y/> | one or the other |
| 0 && ... | prints 0! |
Summary
Use early returns, two ampersands, or ternaries to show things conditionally. Next, styling.
Key takeaways- return null
- &&
- ? :
Next up: Styling — className and style