Sikau

React · Day 5 · about 20 min

Conditional rendering

Show different things in different situations.

Sold out!

A dish that's sold out should say so; an empty cart should show a friendly message; an admin sees an extra button. Components decide what to show with ordinary JavaScript.

Three patterns

function Dish({ name, stock }) {
  if (stock === 0) {
    return <li className="sold-out">{name} — sold out</li>;
  }
  return (
    <li>
      {name} {stock < 5 ? <em>(only {stock} left!)</em> : null}
      {stock > 50 && <strong> Popular</strong>}
    </li>
  );
}

export default function Menu() {
  return (
    <ul>
      <Dish name="Momo" stock={80} />
      <Dish name="Sel roti" stock={3} />
      <Dish name="Yomari" stock={0} />
    </ul>
  );
}

The rest of this lesson

  • Choosing a patternexplain
  • Hiding vs not renderingexplain
  • What renders?predict
  • A stray zeropredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of React