Handling events

Topic 1 of 4 in Interactivity & state6 min readIntermediateFree course

Overview

Interfaces react to users: clicks, typing, hovering, submitting forms, pressing keys. In React you respond to these by attaching event handlers — functions React calls when an event happens. This lesson covers how to write them; the next lesson uses them to update state.

Adding an event handler

JSX
function EnrollButton() {
  function handleClick() {
    alert('Thanks for enrolling!');
  }

  return <button onClick={handleClick}>Enrol</button>;
}

Three steps: define a function inside the component, then pass it as a prop to the element. React event props are camelCase versions of the DOM events: onClick, onChange, onSubmit, onKeyDown, onFocus, onBlur, onMouseEnter, onPointerDown, onScroll…

You can also write the handler inline:

JSX
<button onClick={() => alert('Thanks for enrolling!')}>Enrol</button>

Inline arrows are fine for short handlers; named handleX functions are easier to read when there’s more logic.

Pass the function, don’t call it

The most common beginner bug:

JSX
<button onClick={handleClick}>   // ✓ passes the function; React calls it on click
<button onClick={handleClick()}> // ✗ calls it NOW, during render, on every render

With parentheses, handleClick() runs while the component renders, and its return value (undefined) becomes the handler. If the handler updates state, you get an infinite render loop.

Passing arguments

When the handler needs data, wrap the call in an arrow function:

JSX
function LessonList({ lessons, onComplete }) {
  return (
    <ul>
      {lessons.map((lesson) => (
        <li key={lesson.id}>
          {lesson.title}
          <button onClick={() => onComplete(lesson.id)}>Mark done</button>
        </li>
      ))}
    </ul>
  );
}

The arrow is created during render but only called when the button is clicked.

Handlers can read props and state

Because handlers are defined inside the component, they can use its props and state directly:

JSX
function ShareButton({ course }) {
  async function handleShare() {
    await navigator.clipboard.writeText(`https://academy.example/courses/${course.slug}`);
    alert(`Link to “${course.title}” copied!`);
  }
  return <button onClick={handleShare}>Share</button>;
}

Passing handlers as props

Often the parent decides what should happen, and the child decides when:

JSX
function Button({ onClick, children }) {
  return <button className="btn" onClick={onClick}>{children}</button>;
}

function CoursePlayer({ course }) {
  return (
    <div>
      <Button onClick={() => playVideo(course.videoUrl)}>Play</Button>
      <Button onClick={() => downloadNotes(course.id)}>Download notes</Button>
    </div>
  );
}

Name event-handler props starting with on — onPlay, onDelete, onSelect — so they read like built-in events. Only built-in elements like <button> attach real browser listeners; for your own components, onPlay is just a prop name you choose.

The event object

React passes the handler an event object — a cross-browser wrapper around the native DOM event with the same properties you know:

JSX
function SearchBox() {
  function handleKeyDown(e) {
    if (e.key === 'Escape') {
      e.currentTarget.value = '';
    }
  }
  return <input onKeyDown={handleKeyDown} onChange={(e) => console.log(e.target.value)} />;
}

Useful properties: e.target (the element that triggered the event), e.currentTarget (the element the handler is attached to), e.key, e.shiftKey, e.clientX. The original browser event is available as e.nativeEvent.

Propagation

Events bubble: a click on a button also triggers onClick handlers on its parents, from the inside out:

JSX
<div className="card" onClick={() => openCourse(course.id)}>
  <h2>{course.title}</h2>
  <button onClick={() => addToWishlist(course.id)}>♡</button>
</div>

Clicking ♡ adds to the wishlist and then opens the course — probably not what you want. Stop the event from bubbling with stopPropagation():

JSX
<button
  onClick={(e) => {
    e.stopPropagation();
    addToWishlist(course.id);
  }}
>
  ♡
</button>

All React events bubble except onScroll. To handle an event before children see it, use the capture version: onClickCapture.

Accessibility note: a clickable <div> isn’t focusable and doesn’t respond to the keyboard. For whole-card links, prefer a real <a> or <button> — see Accessibility.

Preventing default behaviour

Some elements have built-in browser behaviour: a submitted <form> reloads the page; a clicked link navigates. Stop it with preventDefault():

JSX
function SearchForm({ onSearch }) {
  function handleSubmit(e) {
    e.preventDefault();                       // don't reload the page
    const formData = new FormData(e.currentTarget);
    onSearch(formData.get('q'));
  }

  return (
    <form onSubmit={handleSubmit}>
      <input name="q" />
      <button type="submit">Search</button>
    </form>
  );
}

stopPropagation() and preventDefault() are unrelated: one stops handlers on parent elements, the other stops the browser’s default action. (React 19 also lets you pass a function to a form’s action prop, which handles this for you — see Form actions.)

Side effects belong in handlers

Components must be pure while rendering, but event handlers don’t run during rendering — they run in response to the user. So they’re exactly where side effects belong: updating state, sending requests, navigating, writing to localStorage, playing sounds, logging analytics.

Remember: onClick={fn} hands React a function to call later. onClick={fn()} calls it right now. When in doubt, wrap it: onClick={() => fn(arg)}.

Exercise

A toolbar with event props

Write a Toolbar that renders two buttons, “Play” and “Upload”, and receives onPlay and onUpload props. Wrap both buttons in a <div> whose onClick logs “toolbar clicked”. Clicking “Play” should call onPlay but must NOT trigger the div’s handler; clicking “Upload” should call onUpload and let the click bubble. Also add a search <form> whose submit handler prevents the page reload and calls onSearch with the input’s current value.

JavaScript
export function Toolbar({ onPlay, onUpload, onSearch }) {
  // your code here
}

Summary

  • Attach handlers with camelCase props like onClick, onChange and onSubmit.
  • Pass a function — onClick={handleClick} — never call it: onClick={handleClick()} runs during render.
  • Use an inline arrow to pass arguments: onClick={() => remove(id)}.
  • Handlers receive an event object; use e.stopPropagation() to stop bubbling and e.preventDefault() to stop browser defaults.
  • Event handlers are where side effects belong — they don’t need to be pure.