React ยท Chapter 8 of 42

Conditional Rendering

React lets you render different UI based on conditions, using regular JavaScript: if statements, ternary operators, or logical `&&`.

Because JSX is just JavaScript, there's no special conditional syntax โ€” you use familiar JS constructs inside `{}`.

Ternary operator

`{condition ? <A /> : <B />}` renders one of two elements depending on a condition.

Logical AND

`{condition && <A />}` renders `<A />` only if condition is truthy, and nothing otherwise.

Example 1 (jsx)
function Status({ isLoggedIn }) {
  return (
    <p>{isLoggedIn ? "Welcome back!" : "Please log in."}</p>
  );
}
Output
Welcome back! (or Please log in.)

The ternary chooses which message to render.

Key points

  • Conditional rendering uses plain JavaScript, not special JSX syntax.
  • Ternaries `? :` render one of two options.
  • `&&` renders content only when a condition is true.
  • Returning `null` from a component renders nothing.
๐Ÿ’ก Note: Be careful with `&&` and numeric 0 โ€” `{count && <p>...}</p>}` renders '0' if count is 0.

๐Ÿ“ Quick Quiz

1. Which operator renders content only if true?

2. What does returning null from a component do?

3. Which is a valid way to conditionally render in JSX?