Skip to main content
⚑ OpenDevDocs
React
frontendreactGuideBeginner

Conditional Rendering in React

Techniques for conditional UI rendering: ternary operators, logical AND (&&), if/else return statements, and preventing the zero rendering bug.

Verified: 2026-09-30
Tested on:react 19.x
Platforms:
web
#react#conditional-rendering#jsx#ternary

Conditional Rendering in React

In React, you can render different JSX elements depending on component props or state values using standard JavaScript branching logic.


1. Ternary Operator (condition ? trueJSX : falseJSX)

Best for switching between two visual states (e.g. Logged In vs. Logged Out):

export function AuthButton({ isLoggedIn }: { isLoggedIn: boolean }) {
  return (
    <div>
      {isLoggedIn ? (
        <button type="button">Dashboard</button>
      ) : (
        <button type="button">Sign In</button>
      )}
    </div>
  );
}

2. Logical AND Operator (&&) & The "Zero Bug"

Use && to render an element only when a condition is true:

{unreadMessages.length > 0 && (
  <span className="badge">{unreadMessages.length}</span>
)}

3. Early Return Guard Clauses

Return early with null or a loading skeleton to keep component bodies clean:

export function UserProfile({ user, isLoading }: { user: User | null; isLoading: boolean }) {
  if (isLoading) {
    return <div className="skeleton-loader">Loading profile...</div>;
  }

  if (!user) {
    return <div className="error-card">User not found.</div>;
  }

  return (
    <div>
      <h2>{user.name}</h2>
      <p>{user.email}</p>
    </div>
  );
}

On this page