REACT Lesson 10 – Conditional Rendering | Dataplexa
LESSON 10

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>
  );
}
DataFlow Dashboard

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.

The ternary operator shines when you have two clear alternatives. But what happens when you only want to show something conditionally, without an alternative? That's where logical AND comes in.

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>
  );
}
DataFlow Dashboard

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.

But be careful with logical AND. There's a common gotcha that trips up developers.

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>
  );
}
DataFlow Dashboard

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>
  );
}
DataFlow Dashboard

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.

This approach works great for complex conditions, but there's another pattern that's perfect when you have many possible outcomes.

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>
  );
}
DataFlow Dashboard
This pattern scales beautifully. Adding new roles is as simple as adding a new key to the object. The fallback using || 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

Real applications like Airbnb's search results use conditional rendering extensively. They show loading skeletons during API calls, empty states when no properties match your filters, and error messages when something goes wrong. Each state provides clear feedback to users about what's happening. Netflix's interface conditionally renders different layouts based on screen size, user subscription level, and viewing history. Their "Continue Watching" section only appears when you have partially watched content. The "Download" button only shows for mobile users with premium subscriptions. Your DataFlow dashboard will use these same patterns. Show different chart types based on selected metrics. Display admin controls only for admin users. Hide sensitive data from guest accounts. Each conditional render makes your app smarter and more user-friendly.

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.