JSX Conditional Rendering Explained: JavaScript + React Rules

JSX Conditional Rendering Isn’t Magic — It’s JavaScript + React Rules If you’ve ever been confused by code like this: {list.length && <List />} and wondered “Why is 0 rendering?” — this post is for you. The confusion comes from mixing JavaScript evaluation rules with React rendering rules. They happen in two different phases. 🟨 Phase 1: JavaScript (Evaluation) Before React does anything, JavaScript evaluates the expression. Key rule of &&: A && B If A is falsy → return A If A is truthy → return B Falsy values in JS: false, 0, "", null, undefined, NaN Important: && returns a value, not true or false Arrays ([]) are truthy 0 is falsy, but still a number Example: 0 && <List /> // → 0 true && <List /> // → <List /> false && "Hi" // → false JavaScript stops here. 🟦 Phase 2: React (Rendering) React now receives the result and decides whether it can be rendered. 🚫 React does NOT render: false true null undefined ✅ React DOES render: 0 "" "hello" NaN Why? Booleans are control flags null / undefined mean absence Numbers & strings are real UI data ❌ The Classic Bug {list.length && <List />} If list = []: list.length === 0 0 && <List /> // JS returns 0 React receives 0 → renders 0 😬 ✅ Correct Patterns Render only when list has items: {list.length > 0 && <List />} Render when list exists: {list && <List />} Render empty state: {!list.length && <EmptyState />} 🧠 Mental Model (Remember This) JavaScript decides WHAT the expression evaluates to React decides WHETHER that result is renderable Falsy ≠ hidden Only false, null, and undefined are hidden by React. 🔑 Final Takeaway JSX isn’t inconsistent — it’s predictable once you separate JavaScript rules from React rules. Most “weird JSX bugs” disappear the moment you think in these two phases. 💬 Have you ever accidentally rendered 0 in production? You’re definitely not alone. #React #JavaScript #JSX #Frontend #WebDevelopment #ReactTips #Engineering

  • text

To view or add a comment, sign in

Explore content categories