Conditional Rendering

Easy

Conditional rendering in React works the same way conditions work in JavaScript. You use ternary operators, logical && short-circuit evaluation, or early returns to decide which elements to render based on component state or props.

Interactive Visualization

Key Points

  • Ternary operator renders one of two elements based on a condition
  • Logical && renders an element only when the condition is truthy
  • Early return exits the component before rendering for guard clauses
  • Returning null from a component renders nothing
  • Switch statements or object maps handle multiple conditions cleanly
  • Be careful with && and falsy numbers: 0 && <X/> renders 0

Code Examples

Conditional Patterns

interface StatusProps {
  isLoggedIn: boolean
  isAdmin: boolean
  notifications: number
}

function StatusBar({ isLoggedIn, isAdmin, notifications }: StatusProps) {
  // Early return guard
  if (!isLoggedIn) {
    return <button>Sign In</button>
  }

  return (
    <div>
      {/* Ternary for two branches */}
      {isAdmin ? <AdminPanel /> : <UserPanel />}

      {/* && for conditional rendering (safe with > 0) */}
      {notifications > 0 && (
        <span>You have {notifications} new messages</span>
      )}
    </div>
  )
}

Early returns handle guard conditions, ternaries handle two branches, and && handles optional elements

Mapping Conditions to Components

type Status = 'loading' | 'error' | 'success'

interface StatusViewProps {
  status: Status
  data?: string
  error?: string
}

const statusComponents: Record<Status, React.FC<StatusViewProps>> = {
  loading: () => <div>Loading...</div>,
  error: ({ error }) => <div>Error: {error}</div>,
  success: ({ data }) => <div>Data: {data}</div>,
}

function DataView(props: StatusViewProps) {
  const Component = statusComponents[props.status]
  return <Component {...props} />
}

An object map cleanly replaces long if-else or switch chains when mapping a finite set of conditions to components

Common Mistakes

  • Using 0 && <Component /> which renders the number 0 instead of nothing
  • Complex nested ternaries that should be refactored into separate components
  • Forgetting that && evaluates the left side and returns it when falsy

Interview Tips

  • Explain the 0 && gotcha and how to fix it with Boolean() or > 0
  • Discuss when to use early returns vs ternaries vs && for clarity
  • Know that returning null hides a component completely

Related Concepts