๐ฏ 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 prints0.
Finished reading & practising?
Saved in this browser. Create a free account to keep it forever.