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.

GroupRendering & State
KindPattern
SinceEarliest 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏