Conditional Rendering

Show different UI based on state, props, and logical conditions

Overview

React renders whatever your component returns. Use JavaScript conditionals—if, ternary (? :), logical AND (&&), and early returns—to control what appears on screen.

Syntax / Usage

function StatusMessage({ status }) {
  // Early return
  if (status === 'loading') return <Spinner />
  if (status === 'error') return <ErrorBanner />

  return <Content />
}

function Greeting({ user }) {
  return (
    <div>
      {/* Ternary */}
      {user ? <p>Welcome, {user.name}</p> : <p>Please log in</p>}

      {/* Logical AND — beware falsy numbers */}
      {user?.isAdmin && <AdminPanel />}

      {/* Explicit boolean */}
      {items.length > 0 && <ItemList items={items} />}
    </div>
  )
}

Switch on discriminated unions for exhaustive handling:

function RequestState({ state }) {
  switch (state.type) {
    case 'idle': return null
    case 'loading': return <Spinner />
    case 'success': return <DataView data={state.data} />
    case 'error': return <Error message={state.error} />
    default: {
      const _exhaustive = state
      return null
    }
  }
}

Examples

Form validation message:

{errors.email && (
  <p role="alert" className="text-red-600">{errors.email}</p>
)}

Tabbed interface:

{activeTab === 'profile' && <ProfileTab />}
{activeTab === 'settings' && <SettingsTab />}

Common Mistakes

  • {count && <Badge />} renders 0 when count is 0—use count > 0 && or ternary
  • Nested ternaries that hurt readability—extract subcomponents or variables
  • Not handling loading and error states in async UIs
  • Rendering undefined in unexpected places when optional chaining fails silently

See Also

jsx use-state use-effect components