LESSON 05 / 05

Conditional Rendering

Show different UI for different situations with &&, the ternary, early returns and a lookup object.

๐ŸŽ“Mediumlevel
โฑ๏ธ25 minto finish
โœ๏ธ2activities

๐Ÿ“‚ Components & JSX๐Ÿท๏ธ React

๐ŸŽฏ By the end of this lesson you canโ€ฆ

  • Render conditionally with && and ? :
  • Return early for special states
  • Avoid the 0-renders-0 trap
โš›๏ธ React App.jsx ๐Ÿ‘† Tap a line to explain it
1function Inbox({ messages }) {2  if (messages.length === 0) return <p>๐Ÿ“ญ No messages yet.</p>;3  return (4    <div>5      <p>๐Ÿ“ฌ You have {messages.length} message{messages.length === 1 ? "" : "s"}.</p>6      {messages.length > 5 && <p>โš ๏ธ Your inbox is getting full!</p>}7    </div>8  );9}10 11function App() {12  return (13    <>14      <Inbox messages={[]} />15      <Inbox messages={["Hi", "Lunch?"]} />16    </>17  );18}
๐Ÿ”ฎ What will this display?
What appears on screen for <p>{items.length && "You have items"}</p> when items is empty?

Many states: use a lookup object

Real screens have more than two states: loading, error, empty, ready. Instead of a tower of nested ternaries, keep one entry per state in an object and pick from it.

โš›๏ธ React App.jsx ๐Ÿ‘† Tap a line to explain it
1const STATUS = {2  loading: { icon: "โณ", text: "Loading your lessonsโ€ฆ" },3  error: { icon: "๐Ÿ˜ต", text: "Something went wrong." },4  empty: { icon: "๐ŸŒฑ", text: "No lessons yet โ€” start one!" },5  ready: { icon: "โœ…", text: "All set." },6};7 8function Status({ state }) {9  const s = STATUS[state] ?? STATUS.error;10  return <p style={{ fontSize: 20 }}>{s.icon} {s.text}</p>;11}12 13function App() {14  return (15    <>16      {["loading", "empty", "ready", "oops"].map((st) => <Status key={st} state={st} />)}17    </>18  );19}
๐Ÿ› ๏ธ Password strength

Build a password input. Below it show nothing while itโ€™s empty, ๐Ÿ”ด Too short under 6 characters, ๐ŸŸก Add a number if it has no digit, and otherwise ๐ŸŸข Strong.

๐Ÿ“Œ Key takeaways

  • {isLoggedIn && <Logout />} shows something only when true.
  • {isVip ? <Gold /> : <Regular />} chooses between two.
  • {count > 0 && โ€ฆ} not {count && โ€ฆ} โ€” otherwise React prints 0.

Finished reading & practising?

Saved in this browser. Create a free account to keep it forever.