Conditional Rendering
Last updated: 2026-11-02
Conditional Rendering Conditional Rendering
React has no if tag: conditional rendering means writing ordinary JavaScript logic — if statements, ternaries, && — inside JSX so that state decides which piece of UI to render, or whether to return null. That is how one component can present a completely different interface in different situations. The four common idioms are the ternary, &&, an early return and precomputed variables.
| Group | Rendering & State |
|---|---|
| Kind | Pattern |
| Since | Earliest React versions |
ℹ️ Info The editor transpiles JSX to JavaScript and renders the real UI in a sandbox; components mount automatically — no manual render call needed.
📝 Syntax
{isLoggedIn ? <UserPanel /> : <LoginButton />} // Ternary: pick one of two
{unread > 0 && <Badge count={unread} />} // &&: render it or render nothing
if (!ok) return null // Early return: render nothing at all
Returns:No return value — a coding convention and mental model.
▶ Example
The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.
Output:
At first the panel shows "Please log in first" with a button; after logging in a welcome message and "You have 3 unread messages" appear; clicking "Mark all as read" removes the unread notice and shows "All messages read".
💡 Key Points
⚠️ Warning When the left side of && is the number 0, the page renders "0" (0 && ... evaluates to 0), so write unread > 0 && instead.
💡 Tip When the branches are many and complicated, extract the decision into a function or return early instead of nesting ternaries into one big JSX blob.
ℹ️ Info Returning null means the component renders nothing, which is handy for hiding an entire component when the user lacks permission.
🏷️ More Rendering & State
💡 Related Cases
More case studies coming soon.
📚 Related Tutorials
❓ FAQ
Q What are the ways to write conditional rendering in React?
A Four common ones: the ternary operator (choose one of two), && (render it or render nothing), an early return, and extracting branches into variables or functions before embedding them in JSX.
Q What if && renders the number 0?
A Because 0 && x evaluates to 0 and gets rendered. Turn the condition into a comparison such as count > 0 && ..., or use a ternary to avoid it.
Q Can I write if-else directly inside JSX?
A No, only expressions fit inside braces. Compute a variable with an if before the return, or use a ternary to express the branch inside JSX.