Skip to content

Lesson 6 of 37Thinking in React

Handling Events

Respond to clicks, typing and form submits, pass handlers correctly, and control event bubbling.

13 min read0/5 questions

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.

React
import { useState } from "react"; export default function App() { const [clicks, setClicks] = useState(0); function handleClick() { setClicks(clicks + 1); console.log("clicked!"); } return ( <div style={{ display: "flex", gap: 8 }}> <button onClick={handleClick}>Named handler ({clicks})</button> <button onClick={() => console.log("inline arrow")}>Inline arrow</button> </div> );}

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 writeWhat React receivesResult
onClick={handleClick}the functionruns on click
onClick={() => remove(id)}a new function that calls remove(id)runs on click, with an argument
onClick={handleClick()}whatever handleClick returnedruns during render, not on click
onClick={remove(id)}whatever remove(id) returnedremoves the item immediately

When you need to pass an argument, wrap it in an arrow function: onClick={() => remove(item.id)}.

Quick check
You want to delete a todo when its button is clicked. Which is correct?
Need a nudge? A hint rules out a wrong answer.

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
import { useState } from "react";import type { ChangeEvent, KeyboardEvent } from "react"; export default function App() { const [text, setText] = useState(""); const [lastKey, setLastKey] = useState(""); function handleChange(e: ChangeEvent<HTMLInputElement>) { setText(e.target.value); } function handleKeyDown(e: KeyboardEvent<HTMLInputElement>) { setLastKey(e.key); } return ( <div> <input aria-label="Type here" value={text} onChange={handleChange} onKeyDown={handleKeyDown} /> <p>You typed: {text}</p> <p>Characters: {text.length}. Last key: {lastKey || "none"}</p> </div> );}

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 pairs0/4 matched

Match the handler to its TypeScript event type.

Choose an item, then its match on the other side.

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.

React
import { useState } from "react";import type { FormEvent } from "react"; export default function App() { const [names, setNames] = useState<string[]>([]); const [draft, setDraft] = useState(""); function handleSubmit(e: FormEvent<HTMLFormElement>) { e.preventDefault(); // stop the page reload if (!draft.trim()) return; setNames([...names, draft.trim()]); setDraft(""); } return ( <form onSubmit={handleSubmit}> <input aria-label="Name" value={draft} onChange={(e) => setDraft(e.target.value)} /> <button type="submit">Add</button> <ul> {names.map((n, i) => ( <li key={i}>{n}</li> ))} </ul> </form> );}

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.

React
import { useState } from "react"; export default function App() { const [log, setLog] = useState<string[]>([]); // The (l) => form adds to the latest list. The state-as-a-snapshot lesson explains why. const add = (msg: string) => setLog((l) => [...l, msg]); return ( <div> <div onClick={() => add("card clicked")} style={{ border: "1px solid #ccc", padding: 12, cursor: "pointer" }}> <strong>Card</strong> (click anywhere) <div style={{ marginTop: 8, display: "flex", gap: 8 }}> <button onClick={() => add("bubbling button")}>Bubbles</button> <button onClick={(e) => { e.stopPropagation(); add("stopped button"); }} > Stops </button> </div> </div> <button onClick={() => setLog([])} style={{ marginTop: 8 }}>Clear log</button> <ol> {log.map((line, i) => ( <li key={i}>{line}</li> ))} </ol> </div> );}
A click bubbling up the tree
AppTitleBubblesButtononClick: "bubbling button"StopsButtononClick: stopPropagation()ActionsCardonClick: "card clicked"root

The click starts at the target, the Bubbles button. Its handler runs first.

1/4

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.

Predict the outputJavaScript

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>
Need a nudge? Hints walk you through it.
Quick check
What is the difference between preventDefault() and stopPropagation()?
Need a nudge? A hint rules out a wrong answer.

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.

React
import { useState } from "react"; function LikeButton({ liked, onToggle }: { liked: boolean; onToggle: () => void }) { return <button onClick={onToggle}>{liked ? "Liked" : "Like"}</button>;} export default function App() { const [liked, setLiked] = useState(false); function handleToggle() { setLiked(!liked); } return ( <div> <LikeButton liked={liked} onToggle={handleToggle} /> <p>{liked ? "You liked this post." : "Not liked yet."}</p> </div> );}

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.

Put it in order5 steps

Order what happens when a user presses Enter in a React form input.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
ChallengeEasy

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 (an matches Banana, Mango and Orange; AP matches 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.

React
import { useState } from "react"; const FRUITS = ["Apple", "Banana", "Cherry", "Mango", "Orange", "Grape"]; export default function App() { return ( <div> <input type="text" aria-label="Filter" /> <ul> {FRUITS.map((f) => ( <li key={f}>{f}</li> ))} </ul> </div> );}
ChallengeMedium

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 as Selected: 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
React
import { useState } from "react"; export default function App() { const [people, setPeople] = useState(["Ada", "Sam", "Priya"]); const [selected, setSelected] = useState("none"); function handleRemove(name: string) { setPeople(people.filter((p) => p !== name)); } return ( <div> <p>Selected: {selected}</p> {people.map((name) => ( <div key={name} className="card" onClick={() => setSelected(name)}> <span>{name}</span> <button onClick={() => handleRemove(name)}>Remove</button> </div> ))} </div> );}
Key terms
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.