⚛️

Conditional Rendering Techniques in React

Apr 23, 2025

Conditional Rendering in React

Overview

React allows components to conditionally render JSX based on certain conditions using JavaScript syntax such as if statements, &&, and the ?: ternary operator. This enables dynamic rendering of components based on the given conditions.

Key Learning Objectives

  • Return different JSX based on conditions
  • Conditionally include or exclude JSX
  • Learn common conditional syntax shortcuts in React

Conditionally Returning JSX

  • Example: PackingList with Item components that may be marked as packed.
    • Items get a checkmark if isPacked is true.
    • Use if/else statements to return different JSX trees.
function Item({ name, isPacked }) {
  if (isPacked) {
    return <li className="item">{name} </li>;
  }
  return <li className="item">{name}</li>;
}

Returning Nothing with null

  • Sometimes, you may want to render nothing. Return null to prevent rendering.
  • Example:
if (isPacked) {
  return null;
}
return <li className="item">{name}</li>;

Conditionally Including JSX

  • Avoid duplication by conditionally including JSX using syntax shortcuts.
  • Ternary Operator (?:):
return (
  <li className="item">{isPacked ? name + ' ' : name}</li>
);
  • Logical AND Operator (&&): Conditional rendering if true, otherwise render nothing.
return (
  <li className="item">{name} {isPacked && ''}</li>
);

Conditional Operator (Ternary ? :)

  • Use it to determine what to render based on a condition.
  • E.g., wrapping text in <del> if the item is packed.
function Item({ name, isPacked }) {
  return (
    <li className="item">
      {isPacked ? (
        <del>
          {name + ' '}
        </del>
      ) : (
        name
      )}
    </li>
  );
}

Logical AND Operator (&&)

  • Conditionally render JSX if the condition is true.
  • Pitfall: Avoid using numbers directly in logical operations to prevent rendering unwanted values.

Conditionally Assigning JSX to a Variable

  • Use let to assign and reassign JSX based on conditions.
let itemContent = name;
if (isPacked) {
  itemContent = name + " ";
}
return (
  <li className="item">{itemContent}</li>
);

Recap

  • Control branching logic in React using JavaScript.
  • Conditionally return JSX with if, save JSX to a variable, and use conditional operators for flexibility.
  • Use {cond ? <A /> : <B />} and {cond && <A />} for conditional rendering.

Challenge

  • Show an icon for incomplete items using ?: when isPacked is not true.
function Item({ name, isPacked }) {
  return (
    <li className="item">
      {name} {isPacked ? '' : '?'}
    </li>
  );
}