~/hackweb.dev
Conditional Rendering
Quiz
...

Conditional Rendering

beginner · updated Tue Sep 08 2026Contribute

Show or hide elements based on conditions in React.

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:

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:

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:

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:

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:

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