React Conditional Rendering

Render dynamic user interfaces using ternary operators, logical AND gates, early returns, and switch guards.

TL;DR

  1. Control rendered JSX output using standard JavaScript if branch conditions.
  2. Inline alternate elements inline with readable ? ternary conditional operators.
  3. Gate single UI elements conditionally using && logical conjunction syntax.

Inline Conditional Syntax

    Ternary Operator

    Choose between two elements based on a boolean predicate.

    return (
      <View>
        {isLoggedIn ? <Dashboard /> : <Login />}
      </View>
    );
    Logical AND Gate

    Render element only when condition evaluates to true.

    return (
      <View>
        {hasNotice && <Badge count={3} />}
      </View>
    );
    Safe Numeric Gate

    Coerce count to boolean to avoid printing zero digits.

    return (
      <View>
        {items.length > 0 && <ItemList items={items} />}
      </View>
    );

Early Return Patterns

    Loading Screen Guard

    Return dedicated loading UI before accessing data.

    if (isLoading) {
      return <Spinner label="Fetching data..." />;
    }
    Error Guard Return

    Halt normal rendering when an error is present.

    if (error) {
      return <Alert status="error" text={error.msg} />;
    }
    Null Guard

    Return null to render completely nothing in the DOM.

    if (!shouldDisplay) {
      return null;
    }

Multi-State Rendering

    Dictionary Mapping

    Map enum string keys to corresponding JSX elements.

    const views: Record<string, JSX.Element> = {
      home: <HomeTab />,
      feed: <FeedTab />,
    };
    return views[currentTab] ?? <DefaultTab />;
    Switch Statement

    Branch across multiple states inside helper functions.

    function renderStatus(status: Status) {
      switch (status) {
        case 'idle': return <StatusBadge text="Ready" />;
        case 'busy': return <Spinner />;
        case 'done': return <CheckMark />;
      }
    }
    Variable Assignment

    Assign JSX to a local variable using conditional blocks.

    let banner;
    if (isHoliday) {
      banner = <HolidayBanner />;
    }
    return <Layout>{banner}</Layout>;

Conditional Styles and Classes

    Template String Classes

    Toggle CSS class names conditionally using template literals.

    <Button className={`btn ${isActive ? 'active' : ''}`}>
      Toggle
    </Button>
    Array Filter Join

    Assemble class strings cleanly from filtered arrays.

    const cls = [
      'card',
      isPrimary && 'primary',
      isDisabled && 'disabled',
    ].filter(Boolean).join(' ');
    Conditional Attributes

    Conditionally pass or omit optional JSX attributes.

    <Button disabled={isSubmitting || !isValid}>
      Submit
    </Button>

Tips

  1. Avoid using numbers directly on the left of && because zero values accidentally render in the DOM.
  2. Extract complex multi-branch rendering logic into standalone subcomponents or clean Record dictionary maps for readability.

Warnings

  1. Never write 0 && <Tag /> because JavaScript evaluates falsy zero into the visible digit 0.
  2. Avoid deeply nested ternary operators with multiple ? branches because they rapidly destroy component template readability.

In Practice

FAQ