NelsonLabs
React Fundamentals/Handling Events

Handling Events

React handles events similarly to the DOM but with a few important differences in syntax and how event handlers work.

Event handlers in React
jsx
// onClick, onChange, onSubmit — camelCase in React
function Button() {
  function handleClick(event) {
    console.log("Clicked!", event);
    event.preventDefault();  // same as DOM
  }

  return <button onClick={handleClick}>Click me</button>;
  // Pass the function reference — don't call it: onClick={handleClick()}
  // onClick={handleClick}   ✓ correct
  // onClick={handleClick()} ✗ calls immediately, doesn't work
}

// Inline arrow function — when you need to pass arguments
function List({ items }) {
  return (
    <ul>
      {items.map(item => (
        <li key={item.id} onClick={() => handleSelect(item.id)}>
          {item.name}
        </li>
      ))}
    </ul>
  );
}
Controlled form inputs
jsx
function LoginForm() {
  const [email, setEmail]       = useState("");
  const [password, setPassword] = useState("");

  function handleSubmit(e) {
    e.preventDefault();
    console.log({ email, password });
    // Send to API...
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Email"
      />
      <input
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      <button type="submit">Log in</button>
    </form>
  );
}
// The input is "controlled" — React state drives the displayed value