React - Conditional Rendering

Conditional Rendering

Use JavaScript expressions to decide what to render.

Try it: Login Gate

View source
const { useState } = React;
function LoginGate(){
  const [user, setUser] = useState(null);
  return (
    <div>
      {user ? (
        <>
          <p>Welcome, {user.name}!</p>
          <button onClick={() => setUser(null)}>Logout</button>
        </>
      ) : (
        <button onClick={() => setUser({ name: 'Ada' })}>Login</button>
      )}
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('try-conditional')).render(<LoginGate />);

Syntax primer (for newcomers)

  • Ternary: condition ? A : B to choose between elements.
  • Logical AND: condition && <SomeComponent /> to show something only when true.
  • Fragments: <>...</> group multiple elements without extra DOM.

Vocabulary

  • Ternary: cond ? A : B expression choosing between two values.
  • Logical AND: cond && value renders the right-hand side only if cond is true.

Checks for Understanding

  1. What are two common patterns for conditional UI in React?
  2. When do fragments help with conditional rendering?
Show answers
  1. Ternaries (cond ? A : B) and logical AND (cond && <X />).
  2. When you need to return multiple sibling elements without adding an extra wrapper node.

Exercises

  1. Show a dismissible alert box only when a checkbox is checked.
  2. Render a list with an empty-state message using a ternary.
  3. Add a simulated loading state (e.g., 800ms) that shows a spinner before content.