Event Bubbling
Calling an event on a parent element will trigger events on all parent elements. In the example below, clicking on the p
element will trigger events on the p
, div
and form
elements.
Demo
EventBubbling.js
export const MyComponent = () => {
const style = {
border: "1px solid black",
margin: "10px",
};
const handleClick = (element) => (event) => {
console.log(`${element} tagname: ${event.target.tagName}`);
};
return (
<form style={style} onClick={handleClick("form")}>
FORM
<div style={style} onClick={handleClick("div")}>
DIV
<p style={style} onClick={handleClick("p")}>
P
</p>
</div>
</form>
);
};
Console:
- -no logs-
;
ℹ️
Clicking on the elements in the above example, we can see that no matter how
many events are triggered, event.target
always points to the element
that was clicked.
Stopping Event Bubbling
Using the stopPropagation
method on the event will stop the event from bubbling. In the example below, clicking on the p
element will trigger events only on the p
element.
EventBubbling.js
export const MyComponent = () => {
const style = {
border: "1px solid black",
margin: "10px",
};
const handleClick = (element) => (event) => {
console.log(element);
event.stopPropagation();
};
return (
<form style={style} onClick={handleClick("form")}>
FORM
<div style={style} onClick={handleClick("div")}>
DIV
<p style={style} onClick={handleClick("p")}>
P
</p>
</div>
</form>
);
};
Console:
- -no logs-