Sub topic 3
Bubbling and Capture
Assume you know JavaScript functions, JSX, React components and props, and basic useState. React events let components respond to user actions without manually querying the DOM.
Bubbling and capture
When an event occurs on a nested element, it travels through the DOM tree in phases:
- Capture travels from the outer element toward the target.
- Target reaches the element that was acted on.
- Bubble travels from the target back through its ancestors.
React supports capture handlers by adding Capture to the prop name.
function Panel() {
return (
<div
onClickCapture={() => console.log('capture')}
onClick={() => console.log('bubble')}
>
<button onClick={() => console.log('button')}>Save</button>
</div>
);
}Clicking the button logs capture, button, then bubble.
Stopping propagation
Call event.stopPropagation() when a child action must not trigger an ancestor handler.
function Toolbar() {
return (
<div onClick={() => console.log('toolbar')}>
<button onClick={e => {
e.stopPropagation();
console.log('button');
}}>
Delete
</button>
</div>
);
}This logs only button. Use this sparingly because stopping propagation can hide actions that an ancestor expects.
Mouse, keyboard, and focus events
Common handlers include onClick, onPointerDown, onKeyDown, onFocus, and onBlur. Read properties such as event.key, event.target, and event.currentTarget. target is the original element; currentTarget is the element whose handler is running.
Typing event handlers in TypeScript
Type the event according to the element and event:
function SearchBox() {
function handleKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
if (e.key === 'Enter') console.log(e.currentTarget.value);
}
return <input onKeyDown={handleKeyDown} />;
}Native listeners with `useEffect`
Use a native listener for events outside JSX, such as window events. Always remove the exact same function during cleanup.
useEffect(() => {
function handleKeyDown(e) {
if (e.key === 'Escape') onClose();
}
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [onClose]);How React delegates events
React usually attaches a small number of native listeners near the root, then dispatches events to the matching component handlers. You still write handlers on JSX elements. This delegation reduces listener setup, but it does not remove normal bubbling and capture behavior.
Exercise
Which handler runs first when a button inside a div is clicked: div onClick, div onClickCapture, or button onClick?
Show answer
div onClickCapture runs first, then button onClick, then div onClick.