React
Conditional Rendering
Master if-else logic in JSX to show or hide DataFlow components based on user state and data conditions.
Showing different content based on conditions is fundamental in any application. Your DataFlow dashboard needs to display error messages when API calls fail, show loading spinners during data fetches, and render different components for admin versus regular users. React handles conditional rendering differently than regular JavaScript. You can't use traditional if-else statements directly inside JSX. But React provides several elegant patterns that feel more natural once you understand them. Think of conditional rendering like a bouncer at a club. The bouncer checks your ID (the condition) and either lets you in (renders the component) or turns you away (renders nothing or something else).The Ternary Operator Pattern
The ternary operator is your go-to tool for conditional rendering. It works inside JSX because it returns a value, unlike if-else statements which don't return anything.// DataFlow needs to show different messages based on user status
function WelcomeHeader({ user }) {
return (
<div style={{ padding: '20px', background: '#f8fafc' }}>
{user.isLoggedIn ? (
<h2>Welcome back, {user.name}!</h2>
) : (
<h2>Please log in to view your dashboard</h2>
)}
</div>
);
}
What just happened?
React evaluated user.isLoggedIn and rendered different JSX based on the result. The ternary operator condition ? true : false works perfectly inside JSX curly braces. Try this: Change the isLoggedIn value to see the message switch instantly.
Logical AND for Simple Conditions
When you only want to show content if a condition is true, use the logical AND (&&) operator. React renders the right side only if the left side is truthy.
// DataFlow shows notifications only when there are new alerts
function NotificationBell({ alertCount }) {
return (
<div style={{ position: 'relative', display: 'inline-block' }}>
<div>🔔</div>
{alertCount > 0 && (
<span style={{
position: 'absolute',
top: '-8px',
right: '-8px',
background: '#ef4444',
color: 'white',
borderRadius: '50%',
width: '20px',
height: '20px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: '12px'
}}>
{alertCount}
</span>
)}
</div>
);
}
What just happened?
React evaluated alertCount > 0 and only rendered the red notification badge when the condition was true. When alertCount is 0, React renders nothing for that part. Try this: Notice how the bell with 0 alerts shows no badge at all.
The Falsy Value Trap
JavaScript has falsy values like 0, empty string, null, and undefined. When using logical AND, these values can render in unexpected ways.// WRONG - This will show "0" when no items exist
function BadItemCount({ items }) {
return (
<div>
{items.length && <p>You have {items.length} items</p>}
</div>
);
}
// CORRECT - This properly handles the zero case
function GoodItemCount({ items }) {
return (
<div>
{items.length > 0 && <p>You have {items.length} items</p>}
</div>
);
}
Common Mistake
Using items.length && ... will render "0" when the array is empty because 0 is falsy but still renderable. Always use explicit comparisons like items.length > 0 to avoid this issue.
Multiple Conditions with If Statements
Sometimes you need more complex logic than ternary operators can handle cleanly. Extract that logic into variables or functions before the return statement.// DataFlow status component with multiple conditions
function DataFlowStatus({ isOnline, hasData, isLoading }) {
let statusContent;
if (isLoading) {
statusContent = <div style={{ color: '#f59e0b' }}>⏳ Loading...</div>;
} else if (!isOnline) {
statusContent = <div style={{ color: '#ef4444' }}>🔴 Offline</div>;
} else if (!hasData) {
statusContent = <div style={{ color: '#f97316' }}>⚠️ No data available</div>;
} else {
statusContent = <div style={{ color: '#22c55e' }}>✅ Everything looks good</div>;
}
return (
<div style={{ padding: '20px', border: '1px solid #e5e7eb' }}>
<h3>System Status</h3>
{statusContent}
</div>
);
}
What just happened?
React evaluated the conditions in order and assigned the appropriate JSX to statusContent. This pattern keeps your JSX clean while handling complex logic. Try this: The priority matters - loading always shows first, then offline, then no data.
Switch-Like Patterns with Objects
When you have multiple discrete states, an object mapping can be cleaner than long if-else chains. Think of it like a lookup table.// DataFlow user role component using object mapping
function UserBadge({ userRole }) {
const roleConfig = {
admin: { color: '#dc2626', icon: '👑', label: 'Administrator' },
editor: { color: '#f97316', icon: '✏️', label: 'Content Editor' },
viewer: { color: '#22c55e', icon: '👁️', label: 'Viewer' },
guest: { color: '#64748b', icon: '👤', label: 'Guest User' }
};
const config = roleConfig[userRole] || roleConfig.guest;
return (
<div style={{
display: 'inline-flex',
alignItems: 'center',
gap: '8px',
padding: '8px 16px',
background: config.color + '20',
color: config.color,
borderRadius: '20px',
fontWeight: '600'
}}>
<span>{config.icon}</span>
<span>{config.label}</span>
</div>
);
}
|| roleConfig.guest handles unknown roles gracefully.
Conditional Rendering Best Practices
✅ Do This
Use explicit boolean checks like count > 0 instead of truthy checks
✅ Do This
Extract complex conditions into variables before the return statement
⚠️ Be Careful
Watch out for falsy values like 0 or empty string rendering when you don't want them
💡 Pro Tip
Use object mapping for multiple discrete states instead of long if-else chains
Performance Note
React only re-renders when conditions change. If user.isLoggedIn stays true, React won't rebuild that part of your component tree. This makes conditional rendering very efficient even in complex applications.
Quiz
1. The DataFlow team needs to show a message only when the search results array has items. Which conditional rendering approach avoids showing "0" on the page?
2. Your DataFlow component needs to render different content based on user role, login status, and data loading state. What's the best approach?
3. What happens when you use `{count && Items: {count}}` and count is 0 in React?
Up Next: Lists and Keys
Transform arrays of data into dynamic UI components and understand why React needs keys for efficient rendering.