The Codex / Technologies / React / Event Handling

Event Handling

Responding to clicks, input, and other user interactions in React - synthetic events, passing arguments, and common patterns.

What it is, in plain English: React handles DOM events through a system called SyntheticEvent — a wrapper around the browser's native event that behaves consistently across all browsers. You attach event handlers as JSX props (onClick, onChange, onSubmit) set to a function. Unlike plain HTML, React event handler names are camelCase and you pass a function reference, not a string.

Responding to clicks and input

The basic pattern

function Button() {
  function handleClick() {
    console.log("Clicked!");
  }

  return <button onClick={handleClick}>Click me</button>;
}

// Key differences from plain HTML:
// HTML:  <button onclick="handleClick()">     ← lowercase, string
// React: <button onClick={handleClick}>        ← camelCase, function reference (no parens!)

Common mistake — calling the function instead of passing it

// ✗ WRONG — this calls handleClick IMMEDIATELY during render, not on click:
<button onClick={handleClick()}>Click</button>

// ✓ RIGHT — pass the function itself, React calls it later when clicked:
<button onClick={handleClick}>Click</button>

// ✓ RIGHT — or wrap in an arrow function (needed if passing arguments):
<button onClick={() => handleClick()}>Click</button>

Passing arguments to a handler

function TodoItem({ id, text, onDelete }) {
  return (
    <li>
      {text}
      {/* Need to wrap in arrow function to pass the id argument */}
      <button onClick={() => onDelete(id)}>Delete</button>
    </li>
  );
}

The event object

function Input() {
  const [value, setValue] = React.useState("");

  const handleChange = (event) => {
    console.log(event.target.value);  // the new input value
    setValue(event.target.value);
  };

  return <input value={value} onChange={handleChange} />;
}

// React wraps the native browser event in a SyntheticEvent —
// works consistently across all browsers. Most properties match
// the native DOM event (target, key, preventDefault(), etc.)

preventDefault — stopping default browser behaviour

function Form() {
  const handleSubmit = (event) => {
    event.preventDefault();   // stops the page from reloading on submit
    console.log("Form submitted!");
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" />
      <button type="submit">Submit</button>
    </form>
  );
}
Try It Yourself (JSX)

Official Sources

The Codex links only to official documentation. No third-party tutorials.