Events and forms

Pass data to an event handler

Wrap a call in a small arrow function when the handler needs an item id or another render-time value.

Wrap a call in an arrow function when the handler needs data from the current render:

function Task({ task, onRemove }) {
  return (
    <button onClick={() => onRemove(task.id)}>
      Remove {task.title}
    </button>
  )
}

The arrow function is the event handler. React calls it later. It then calls onRemove with the task ID captured by this render.

Do not write this:

<button onClick={onRemove(task.id)}>Remove</button>

That calls onRemove while rendering.

Pass a stable identifier rather than the list index. If items move, an index can point to a different task by the time the parent updates its state.

You can pass the browser event too when needed:

onClick={event => onRemove(task.id, event)}

Most application handlers need the domain value more than the raw event. Keep the child callback focused on the intent.

Reorder a task list, remove one item, and confirm the correct ID reaches the parent.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →