Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 4.1Responding to events

React events use camelCase props such as onClick, onChange and onSubmit. Pass a function; do not call it while rendering.

Event handlers

JSX
function TaskButton() {
  function handleClick() {
    console.log("Task selected");
  }

  return (
    <button
      className="button button--primary"
      onClick={handleClick}
    >
      Select task
    </button>
  );
}

onClick={handleClick} gives React the function. Writing onClick={handleClick()} calls it immediately. Use an inline arrow function when you need to pass an argument: onClick={() => onDelete(id)}.

Passing handlers

A parent can pass a handler as a prop so a child reports an interaction without owning the data. Name the prop for the meaning of the event, such as onComplete, rather than the physical interaction; the component can later support a keyboard as well as a click.

What happens after a click

  1. Rendering passes a function reference to onClick.
  2. The browser reports a click and React calls that function with an event object.
  3. The handler calculates a value or asks an owner to update state.
  4. If state changes, React renders the affected components again.

Events still propagate through the DOM. Use event.stopPropagation() only when necessary, and avoid nested interactive elements.

Challenge: report which task was clicked

Give TaskItem an id and onDelete prop. Add a Delete button that calls the parent function with that id. Nothing should happen during rendering.

One key example
<button
  className="task__delete button button--danger"
  onClick={() => onDelete(id)}
>
  Delete
</button>

The arrow creates a function for React to call later.

Feedback 👍
Comments are sent via email to me.