Handling events

Interactive apps respond to the user: clicks, typing, hovering, submitting and key presses. In React, you attach event handlers as props.

Click events

React · live preview
Preview

Watch the Console panel under the preview.

⚠️ Pass the function, don't call it: onClick={handleClick} ✓ vs onClick={handleClick()} ✗. The second one runs immediately during render, not on click.

The event object

Handlers receive an event object with details about what happened:

Common events: onClick, onChange, onSubmit, onKeyDown, onMouseEnter, onMouseLeave, onFocus, onBlur, onScroll.

Passing arguments to handlers

Wrap the call in an arrow function:

Preventing default behaviour

Child-to-parent communication: callback props

Props flow down, so how does a child tell its parent something happened? The parent passes a function as a prop, and the child calls it:

This "data down, events up" pattern is the backbone of React apps. By convention, callback props are named onSomething and handler functions handleSomething.

Event propagation

Events bubble up from the clicked element through its parents. Use e.stopPropagation() to stop that:

Practice: a tiny quiz

Build a question with three answer buttons. When one is clicked, show "Correct! 🎉" or "Try again". Disable the buttons once the right answer has been chosen, and add a "Reset" button.

✎ Check your understanding

1.What's wrong with <button onClick={save()}>?

2.How does a child component notify its parent of an event?