Conditional Rendering

Difficulty: Beginner

Conditional rendering in React means showing different UI based on some condition - just like how JavaScript uses if/else to execute different code paths. Since JSX is compiled to JavaScript, you can use all the conditional logic that JavaScript provides. The key is understanding which patterns work in which contexts, because JSX expressions only accept expressions, not statements.

The simplest approach is using an if/else statement before the return. Since the entire return value can be different based on a condition, you can have early returns: `if (isLoading) return <Spinner />;` followed by `if (error) return <Error />;` followed by `return <Content />;`. This is clear and readable, and works well when the entire component output changes based on a condition. Many developers prefer this pattern for its readability.

Inside JSX, you cannot use if/else statements, so you use expressions instead. The ternary operator `condition ? <A /> : <B />` is used when you want to toggle between two different outputs. The logical AND operator `condition && <A />` is used when you want to render something or nothing - if the condition is true, the right side is rendered; if false, nothing is shown (since false, null, and undefined produce no visible output in JSX).

The logical OR operator `||` provides fallback rendering: `{content || <Placeholder />}` renders the content if it is truthy, otherwise falls back to the Placeholder. You can also use the nullish coalescing operator `??` which only falls back for null or undefined (not for other falsy values like 0 or empty string): `{count ?? 'N/A'}` shows 0 if count is 0, but shows 'N/A' if count is null or undefined.

A common pitfall is using `&&` with numeric values. The expression `{items.length && <List />}` will render the number 0 when the array is empty, because 0 is falsy but is a valid renderable value in React. Always use an explicit boolean comparison: `{items.length > 0 && <List />}`. This is one of the most frequent bugs in React applications, so always be explicit about your conditions when using the `&&` pattern.

Code examples

If/Else and Early Returns

function StatusMessage(props) {
  // Early returns for different states
  if (props.isLoading) {
    return 'Loading...';
  }

  if (props.error) {
    return 'Error: ' + props.error;
  }

  if (!props.data) {
    return 'No data available';
  }

  return 'Data: ' + props.data;
}

console.log(StatusMessage({ isLoading: true }));
console.log(StatusMessage({ isLoading: false, error: 'Not found' }));
console.log(StatusMessage({ isLoading: false, error: null, data: null }));
console.log(StatusMessage({ isLoading: false, error: null, data: 'Hello!' }));

Early returns handle each condition at the top of the function. The first matching condition returns immediately, making the logic easy to follow.

Ternary and Logical AND

// Ternary: toggle between two outputs
function AuthStatus(props) {
  const status = props.isLoggedIn ? 'Welcome, ' + props.name : 'Please sign in';
  return status;
}

console.log(AuthStatus({ isLoggedIn: true, name: 'Alice' }));
console.log(AuthStatus({ isLoggedIn: false }));

// Logical AND: show or hide
function Notification(props) {
  const badge = props.count > 0 && (' (' + props.count + ' new)');
  return 'Inbox' + (badge || '');
}

console.log(Notification({ count: 5 }));
console.log(Notification({ count: 0 }));

// PITFALL: 0 renders in JSX!
const items = [];
const bad = items.length && 'Has items';   // 0 (renders!)
const good = items.length > 0 && 'Has items'; // false (hidden)
console.log('Bad: ' + bad);
console.log('Good: ' + good);

Use ternary for A-or-B rendering, && for show-or-nothing. Always use explicit boolean comparisons with && to avoid rendering 0.

Conditional Element Variables

// Store conditional elements in variables before JSX
function UserDashboard(props) {
  let greeting;
  if (props.isAdmin) {
    greeting = 'Admin Dashboard';
  } else {
    greeting = 'User Dashboard';
  }

  const notifications = props.notifications > 0
    ? props.notifications + ' notifications'
    : 'No notifications';

  const premium = props.isPremium ? ' [PREMIUM]' : '';

  return greeting + premium + ' | ' + notifications;
}

console.log(UserDashboard({ isAdmin: true, isPremium: true, notifications: 3 }));
console.log(UserDashboard({ isAdmin: false, isPremium: false, notifications: 0 }));

Storing conditional values in variables before the return keeps JSX clean. Use if/else for complex conditions and ternary for simple ones.

Key points

Concepts covered

if/else rendering, ternary operator, logical AND short-circuit, conditional components, null rendering