React Conditional Rendering
Very often a component should show different things depending on its props or state: a login button or a user menu, a spinner while loading, a warning only if the cart is empty. Because JSX is JavaScript, you use ordinary JavaScript to make these choices.
Option 1: if before the return
The clearest approach for completely different outputs is a plain if statement with an early return:
import { useState } from 'react';
function Greeting({ user }) {
if (!user) {
return <p>Please sign in to see your dashboard.</p>;
}
return <p>Welcome back, <strong>{user.name}</strong>! You have {user.tasks} open tasks.</p>;
}
export default function App() {
const [user, setUser] = useState(null);
return (
<div>
<Greeting user={user} />
{user
? <button onClick={() => setUser(null)}>Sign out</button>
: <button onClick={() => setUser({ name: 'Lan', tasks: 4 })}>Sign in</button>}
</div>
);
}Option 2: the ternary operator
Inside JSX you can't write if, but you can use condition ? a : b. It's perfect when you choose between two small pieces of markup, as the sign-in button above shows.
Option 3: logical &&
When there is no "else" — show something or nothing — use &&. If the left side is truthy, React renders the right side; if it is false, nothing appears:
import { useState } from 'react';
export default function App() {
const [items, setItems] = useState(['Milk', 'Eggs']);
return (
<div>
<h3>Shopping cart</h3>
{items.length > 0 && <p>You have {items.length} item(s): {items.join(', ')}</p>}
{items.length === 0 && <p style={{ color: 'gray' }}>Your cart is empty.</p>}
{items.length >= 3 && <p style={{ color: 'green' }}>🚚 Free delivery unlocked!</p>}
<button onClick={() => setItems([...items, 'Bread'])}>Add bread</button>{' '}
<button onClick={() => setItems([])}>Empty cart</button>
</div>
);
}Watch out: never put a number on the left of
&&.{count && <Badge />}renders0whencountis zero, because0is a valid thing to display. Compare explicitly:{count > 0 && <Badge />}.
Option 4: return null
A component can hide itself by returning null. The parent still renders it, but nothing reaches the screen:
import { useState } from 'react';
function Banner({ show, onClose }) {
if (!show) return null;
return (
<div style={{ background: '#fff3cd', padding: 10, borderRadius: 6, marginBottom: 8 }}>
🎉 New features are available! <button onClick={onClose}>Dismiss</button>
</div>
);
}
export default function App() {
const [show, setShow] = useState(true);
return (
<div>
<Banner show={show} onClose={() => setShow(false)} />
<p>Main page content.</p>
{!show && <button onClick={() => setShow(true)}>Show banner again</button>}
</div>
);
}Option 5: a lookup object
When there are many possible states, a map from state to UI is often neater than a chain of ternaries:
import { useState } from 'react';
const STATUS_UI = {
idle: { icon: '⏸️', text: 'Not started', color: 'gray' },
loading: { icon: '⏳', text: 'Uploading…', color: 'orange' },
success: { icon: '✅', text: 'Upload complete', color: 'green' },
error: { icon: '❌', text: 'Upload failed', color: 'crimson' },
};
export default function App() {
const [status, setStatus] = useState('idle');
const ui = STATUS_UI[status];
return (
<div>
<p style={{ color: ui.color, fontSize: 20 }}>{ui.icon} {ui.text}</p>
{Object.keys(STATUS_UI).map((s) => (
<button key={s} onClick={() => setStatus(s)} disabled={s === status} style={{ marginRight: 4 }}>
{s}
</button>
))}
</div>
);
}Choosing a technique
| Situation | Best fit |
|---|---|
| Completely different output (e.g. loading vs. content) | if + early return |
| Choose between two small elements | cond ? <A /> : <B /> |
| Show something or nothing | cond && <A /> |
| Component decides to hide itself | return null |
| Many named states | lookup object / switch in a helper |
Conditional attributes and classes
Conditions aren't only for whole elements. You can compute attribute values and styles too:
<button disabled={!isValid} className={isActive ? 'tab active' : 'tab'}>
Save
</button>
<li style={{ textDecoration: done ? 'line-through' : 'none' }}>{text}</li>Tip: If your JSX is full of nested ternaries, extract the logic into a variable or a small component. Readability beats cleverness.
Test yourself
What does {count && <Badge />} render when count is 0?
- Nothing
- The Badge
- The number 0
- An error
How can a component render nothing at all?
- return false only inside class components
- return null
- return ''
- throw an error
Which expression shows <Spinner /> while loading and <List /> otherwise?
- {loading && <Spinner /> || <List />}
- {loading ? <Spinner /> : <List />}
- {if (loading) <Spinner />}
- {loading : <Spinner /> ? <List />}