Part 04 / Topic 4 of 8
&&, the ternary, and early return
This course's prerequisites already assume you know && and the ternary as plain JS operators; what changes inside JSX is only that the result of either one can itself be an element, or nothing at all.
| Pattern | Shape | Use it when |
|---|---|---|
condition && <Jsx /> |
"render this, or render nothing" | there is only one outcome worth showing - no meaningful "else" |
condition ? <A /> : <B /> |
"render exactly one of these two" | both outcomes are real UI, never "nothing" |
early return |
"bail out of this whole component for one case" | the special case's JSX barely resembles the main case's, or there is more than one special case to check |
// examples/03_conditional_rendering.jsx
export function StockBadge({ inStock }) {
return inStock ? (
<span className="badge in-stock">In stock</span>
) : (
<span className="badge out-of-stock">Out of stock</span>
);
}
export function DiscountNote({ discountPercent }) {
return <p>{discountPercent > 0 && <span className="discount">{`${discountPercent}% off today`}</span>}</p>;
}
export function MenuItemRow({ item }) {
if (!item.available) {
return (
<li className="unavailable">
<span>{item.name}</span> — temporarily unavailable
</li>
);
}
return (
<li>
<span>{item.name}</span> — {`₹${item.price}`}
</li>
);
}
All three really run (examples/03_conditional_rendering.test.jsx): StockBadge shows exactly one of "In stock"/"Out of stock," never both; DiscountNote with discountPercent={0} renders no .discount element at all, not an empty one; MenuItemRow with available: false returns before its price JSX is ever reached, so screen.queryByText(/₹180/) really finds nothing even though item.price is 180.
Done here? The practice set for Part 4 — including the solutions — is on the part page.