Lesson 6 of 37Thinking in React
Handling Events
Respond to clicks, typing and form submits, pass handlers correctly, and control event bubbling.
A UI that cannot respond to the user is a poster. Events are how clicks, keystrokes and form submits reach your code. The syntax is small, but two mistakes show up in almost every beginner's React code: calling a handler instead of passing it, and forgetting that events bubble up to parent elements. You will see both, live.
Passing a function, not calling it
You attach an event handler with a camelCase prop like onClick, and you give it a function. React calls that function later, when the event happens.
Now the classic bug. onClick={handleClick()} has parentheses, so JavaScript calls handleClick immediately, during render, and passes its return value (undefined) as the handler. Nothing happens on click, and if the function updates state, it re-renders, calls it again, and loops until React gives up with "Too many re-renders".
| You write | What React receives | Result |
|---|---|---|
onClick={handleClick} | the function | runs on click |
onClick={() => remove(id)} | a new function that calls remove(id) | runs on click, with an argument |
onClick={handleClick()} | whatever handleClick returned | runs during render, not on click |
onClick={remove(id)} | whatever remove(id) returned | removes the item immediately |
When you need to pass an argument, wrap it in an arrow function: onClick={() => remove(item.id)}.
The event object
React passes your handler an event object as its first argument. It wraps the browser's event (React calls it a synthetic event) with the same familiar fields: e.target (the element the event started on), e.currentTarget (the element the handler is attached to), e.key for keyboard events, and the methods preventDefault() and stopPropagation().
In TypeScript you type it with React's event types, named after the event and the element:
React's onChange fires on every keystroke, unlike the DOM's native change event, which waits until the input loses focus. That is what makes live filtering and validation easy.
Match the handler to its TypeScript event type.
Forms and preventDefault
Some events have a default action in the browser. Submitting a <form> reloads the page (or navigates to its action URL); clicking a link navigates. In a React app you usually want to handle the submit yourself, so you call e.preventDefault() first.
Handle onSubmit on the form, not onClick on the button: that way pressing Enter in the input submits too, which keyboard users expect. (Index keys are fine here because the list only ever grows at the end.)
Bubbling and stopPropagation
When you click an element, the event fires on that element and then bubbles up through every ancestor, running each one's handler. Click the button below and watch the log: the button's handler runs, then the card's.
The click starts at the target, the Bubbles button. Its handler runs first.
e.stopPropagation() ends the bubbling at that element, so the card never hears about the click. You need it whenever an interactive element sits inside another clickable one: a delete button on a clickable row, a "like" button on a clickable post.
The user clicks the button once. What is logged, in order? (one per line)
<section onClick={() => console.log("section")}>
<div onClick={() => console.log("div")}>
<button onClick={() => console.log("button")}>Go</button>
</div>
</section>preventDefault() and stopPropagation()?Naming: onX props and handleX functions
When your own component accepts a function from its parent, name the prop onSomething (it describes the event) and the function that handles it handleSomething. This mirrors the built-in onClick and makes code scannable.
LikeButton does not know or care what happens on toggle. It reports the event upward, and the parent decides. This "data down, events up" pattern is the backbone of the State unit.
Order what happens when a user presses Enter in a React form input.
- Tap the steps below in the right order.
Live filter
Add a live filter to the fruit list.
- An
<input type="text" aria-label="Filter">above the list. - As the user types, the
<ul>shows only fruits whose name contains the text, ignoring case (anmatches Banana, Mango and Orange;APmatches Apple and Grape). - When nothing matches, render no
<li>items and show<p>No matches</p>instead.
Keep the typed text in state with useState and update it in onChange.
Fix the bubbling bug
Clicking a person's card selects them, and each card has a Remove button. There is a bug: clicking Remove also selects the person you are removing, because the click bubbles up to the card.
Fix it so that:
- Clicking a card shows
Selected: <name>(it starts asSelected: none). - Clicking Remove deletes that card and does not change the selection.
Selected: Sam
[Ada Remove] [Sam Remove] [Priya Remove]
click Remove on Priya → Selected: Sam (unchanged), two cards left- event handler
- A function you pass to a prop like
onClick. React calls it when the event happens. - synthetic event
- React's cross-browser wrapper around the native event, passed to your handlers.
- preventDefault
- Stops the browser's built-in action for the event, like a form submit reloading the page.
- bubbling
- After firing on the target, an event travels up through each ancestor and runs their handlers.
- stopPropagation
- Stops the event from bubbling further, so ancestors' handlers do not run.