Skip to content

Event Handling

Handling DOM events in React, synthetic events, and common patterns for user interaction.

What you'll learn

  • How to attach event handlers in JSX
  • Synthetic events and the React event system
  • Passing arguments to event handlers
  • Preventing default behavior and stopping propagation

Concept

Events in React

React handles events through a system called Synthetic Events. Instead of attaching real DOM event listeners to every element, React attaches a single listener at the root and delegates events. The event object you receive in a handler is a wrapper (SyntheticEvent) that behaves like the native DOM event but works identically across all browsers, eliminating cross-browser inconsistencies.

Attaching Handlers

In React, you attach event handlers as props using camelCase names: onClick, onChange, onSubmit, onMouseOver, etc. You pass a function reference (or inline arrow function) as the value. Unlike HTML attributes, you pass the function itself, not a string of code: onClick={handleClick} not onClick="handleClick()".

Passing Arguments

A common need is to pass extra arguments to an event handler. You have two options. The first is an inline arrow function: onClick={() => handleClick(id)}. The second is using bind: onClick={handleClick.bind(null, id)}. The arrow function approach is more readable and is the recommended pattern in modern React. Be aware that inline arrow functions create a new function on each render, which can have minor performance implications for very hot paths.

preventDefault and stopPropagation

To prevent a form from submitting or a link from navigating, call e.preventDefault() in the handler. To stop an event from bubbling up to parent elements, call e.stopPropagation(). These work exactly like their native DOM counterparts. For form submissions, always call preventDefault() first, then read the form data and handle it with your own logic.

Supported Event Types

React supports a wide range of events: clipboard (onCopy, onPaste), composition, keyboard (onKeyDown, onKeyPress, onKeyUp), focus (onFocus, onBlur), form (onChange, onInput, onSubmit), mouse (onClick, onDoubleClick, onMouseEnter), selection, touch, wheel, and media events. Each has a corresponding SyntheticEvent type. For custom events or non-standard DOM events, you can use native event listeners via refs and the useEffect hook to attach them manually to the DOM node.

Example

              import { useState } from "react";

function TodoList() {
  const [todos, setTodos] = useState(["Learn React", "Build an app"]);
  const [input, setInput] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault(); // Prevent page reload.
    if (!input.trim()) return;
    setTodos([...todos, input.trim()]);
    setInput("");
  };

  const removeTodo = (index) => {
    setTodos(todos.filter((_, i) => i !== index));
  };

  return (
    <form onSubmit={handleSubmit}>
      <input value={input} onChange={e => setInput(e.target.value)}
        placeholder="Add a todo" />
      <button type="submit">Add</button>
      <ul>
        {todos.map((todo, i) => (
          <li key={i}>
            {todo}
            <button onClick={() => removeTodo(i)}>Remove</button>
          </li>
        ))}
      </ul>
    </form>
  );
}
            

onSubmit calls preventDefault to stop the form reload. The remove button uses an inline arrow to pass the index. onChange updates the input state on every keystroke.

Try it

  • Regex Tester

    Validate form input with regular expressions before handling events.

  • HTTP Status Codes

    Understand status codes when your event handlers trigger API calls.

Common mistakes

The mistake

Calling the event handler instead of passing it as a reference

The fix

Write onClick={handleClick}, not onClick={handleClick()}. The latter calls the function immediately during render. Use an arrow function if you need to pass arguments.

The mistake

Forgetting to call e.preventDefault() on form submissions

The fix

Without preventDefault, the browser will reload the page on submit. Always call e.preventDefault() first in your onSubmit handler, then process the form data.

Practice Event Handling

8 exercises

Practice Event Handling

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors