Event Propagation
Event Propagation
Event handlers will also catch events from any children your component might have. We say that an event “bubbles” or “propagates” up the tree: it starts with where the event happened, and then goes up the tree.
export default function Toolbar() {
return (
<div className="Toolbar" onClick={() => alert('You clicked on the toolbar!')}>
<button onClick={() => alert('Playing!')}>Play Movie</button>
<button onClick={() => alert('Uploading!')}>Upload Image</button>
</div>
);
}
If you click on the “Play Movie” button, its onClick will run first (alerting “Playing!”), followed by the parent div’s onClick (alerting “You clicked on the toolbar!”).
Note: All events propagate in React except onScroll, which only works on the JSX tag you attach it to.
Stopping Propagation
If you want to prevent an event from reaching parent components, you need to call e.stopPropagation() on the event object.
Event handlers receive an event object as their only argument. By convention, it’s usually called e, which stands for “event”. You can use this object to read information about the event or stop its propagation.
function Button({ onClick, children }) {
return (
<button onClick={(e) => {
// Prevent the event from bubbling up to parent elements
e.stopPropagation();
onClick();
}}>
{children}
</button>
);
}
Preventing Default Behavior
Some browser events have default behavior associated with them. For example, a <form> submit event, which happens when a button inside of it is clicked, will reload the whole page by default.
You can call e.preventDefault() on the event object to stop this from happening.
export default function Signup() {
function handleSubmit(e) {
// Prevent the browser from reloading the page
e.preventDefault();
alert('Submitting!');
}
return (
<form onSubmit={handleSubmit}>
<input />
<button>Send</button>
</form>
);
}
Summary of e.stopPropagation vs e.preventDefault
e.stopPropagation()stops the event handlers attached to the tags above from firing.e.preventDefault()prevents the default browser behavior for the few events that have it (like form submissions or link clicks).
Interview Questions
Q: How do you stop an event from bubbling up to parent components in React?
A: You call e.stopPropagation() on the React SyntheticEvent inside your event handler. Note that in React 16 and below, you sometimes had to use e.nativeEvent.stopImmediatePropagation(), but modern React handles standard propagation naturally.