~/
hackweb.dev
Conditional Rendering
Quiz
⌘K
...
~/
/tutorials
/react/react-conditional-rendering/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
Comment
0 / 300
Typo
Grammar
Broken link
Clarify
Code
en/tutorials/react/7react-conditional-rendering
Write
Preview
Diff
# Conditional Rendering React lets you render different UI based on conditions. There are several patterns to choose from. ## Ternary Operator The most common inline pattern: ```jsx function Greeting({ isLoggedIn }) { return ( <div> {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>} </div> ); } ``` Keep ternaries short. Complex logic belongs outside JSX. ## Logical AND (`&&`) Render something or nothing: ```jsx function Mailbox({ unreadMessages }) { return ( <div> <h1>Hello!</h1> {unreadMessages.length > 0 && ( <p>You have {unreadMessages.length} unread messages.</p> )} </div> ); } ``` **Gotcha:** `0 && <p>` renders `0`, not nothing. Use `length > 0` explicitly. ## Early Return Exit the component before returning JSX: ```jsx function UserGreeting({ user }) { if (!user) return null; return <h1>Hello, {user.name}!</h1>; } ``` Clean and readable for complex conditions. ## If/Else Outside JSX Use when logic is too complex for inline: ```jsx function Status({ isLoading, data, error }) { if (isLoading) return <Spinner />; if (error) return <ErrorMessage error={error} />; if (!data) return <NoData />; return <DataView data={data} />; } ``` ## Enum Pattern Map states to components: ```jsx function StatusBadge({ status }) { const badges = { active: <span className="green">Active</span>, pending: <span className="yellow">Pending</span>, inactive: <span className="red">Inactive</span>, }; return badges[status] || null; } ``` Readability wins over clever one-liners. ## Best Practices 1. **Use early returns** — For multiple exclusive conditions 2. **Ternaries for two options** — Keep them short 3. **`&&` for show/hide** — One condition, one element 4. **Enum pattern for many states** — Maps are cleaner than switch statements ## Common Mistakes 1. **`0 && <Component>`** — Renders `0` because 0 is falsy but not false 2. **Overly long ternaries** — Use if/else for complex logic 3. **Returning `undefined`** — Always return `null` for empty renders 4. **Nesting ternaries** — Hard to read; use if/else instead
No changes yet
Reset to original
Submit suggestion
cancel