Events and forms

Handle an event

Pass a function to a JSX event prop and let React call it when the interaction occurs.

Event handlers run in response to a user interaction. They are where click-caused work belongs.

function SaveButton() {
  function handleClick() {
    console.log('Saved')
  }

  return <button onClick={handleClick}>Save</button>
}

Click the button once and the console prints Saved. Reload the page and you should not see that message until you click again.

Event prop names use camelCase. Pass the function as onClick={handleClick}.

This is wrong:

<button onClick={handleClick()}>Save</button>

It calls the function during rendering and passes its return value to onClick. The console may log Saved on every render, not on every click.

Put work caused by the interaction in the handler: update state, submit data, or call a parent callback. Keep rendering pure.

Use the semantic element for the interaction. A button already supports keyboard activation, focus, and disabled behavior. A clickable div makes you rebuild those features.

Name handlers after the event or intent: handleClick, handleSave, or onSave. A clear name makes the data flow easier to follow.

React 17 and later attach handlers to the React root, but propagation rules inside your tree still behave like the DOM model. Nested custom components forward events through the same bubbling path unless you stop them.

You can pass arguments by wrapping the handler: onClick={() => saveTask(task.id)}. React still calls your function only when the user clicks, not during render.

Form controls use the same idea with different prop names: onSubmit on the form, onChange on inputs, onClick on buttons.

Add a console log inside the component body and another inside the handler. Reload and click once. Notice which log belongs to rendering and which belongs to the event.

Lesson completed