Conditional Rendering
A book you have finished should say Finished; one you have not should say To read. A card with notes shows a little badge; one without shows nothing. There is no special React syntax for this — you use ordinary JavaScript, placed where JSX can accept it.
The rule
Two choices: ternary. Something or nothing: &&. Nothing at all: return null.
Two choices — the ternary. Inside braces, condition ? a : b picks one of two pieces of markup:
<p>{read ? 'Finished' : 'To read'}</p>Something or nothing — &&. condition && markup shows the markup when the condition is true and nothing when it is false, because React ignores false, null and undefined:
{favourite && <span className="star">★</span>}Nothing at all — early return. A component can stop before its main JSX. An if statement works here because it sits outside the returned markup:
function BookCard({ title, read, notes, hidden }) {
if (hidden) return null;
return (
<article className="book">
<h2>{title}</h2>
<p>{read ? 'Finished' : 'To read'}</p>
{notes > 0 && <span className="badge">{notes} notes</span>}
</article>
);
}For anything more tangled, compute a variable before the return using plain if/else, then drop the variable into the JSX with braces:
let status;
if (read) status = <strong>Finished</strong>;
else if (pagesLeft < 20) status = <em>Almost there</em>;
else status = 'To read';
return <p>{status}</p>;This keeps the markup readable and lets you use every tool JavaScript offers, since the decisions happen outside the JSX.
The shortcut
Count the outcomes before you write anything: two outcomes → ternary; one-or-none → &&; whole component vanishes → early return null.
Then apply one safety check to every &&: is the left side a real true/false?
The tempting code
{notes && <span>{notes} notes</span>}looks like "show the badge if there are notes."
Numbers are the classic trap because 0 is falsy in JavaScript but still a value React will display. Empty strings are skipped, but relying on that makes the intent hard to read, so compare explicitly.
Drills
Answer fast — trust the rule.
A card shows either "Available" or "On loan". Which fits best?
With count = 0, what does {count && <p>New</p>} render?
How can a component render nothing at all when hidden is true?
Which of these values does React render as visible text?
Remember
- Two choices: ternary. Something or nothing:
&&. Nothing at all:return null. - Count the outcomes first; then check every
&&has a real boolean on the left. - Trap:
{count && ...}prints 0.
