Flowers

Event Bubbling

I thought of a very cheeky analogyโ€ฆ. imagine someone slaps you hard on the cheek, the pain doesnโ€™t just stay there, it spreads across your face and even rings in your ears, and often gives you a headache... Trust me, Iโ€™ve received that kind of slap before, from my mom. The sole purpose was to properly reset my brain. ๐Ÿ˜ฎโ€๐Ÿ’จ

Thatโ€™s event bubbling: the event starts at one element and propagates outward through its parent elements.
When working with events in React, you might have noticed that sometimes multiple event handlers get triggered ๐Ÿคทโ€โ™€๏ธ, even when you only clicked one element. Well, That&apso;s due to something called event bubbling, a behavior inherited from how the browser handles events.

๐ŸงจWhat is Event Bubbling?

In the browser, when you click an element, the event doesn&apso;t stop there. It starts from the innermost element and travels up through its parent elements, this is called bubbling.
it is quite similar to ripples in a pond, the disturbance starts at one point and then spreads outward to everything around it.๐Ÿ’ฆ๐ŸŒŠ

For example
<๐™™๐™ž๐™ซ ๐™ค๐™ฃ๐˜พ๐™ก๐™ž๐™˜๐™ ={() => ๐™˜๐™ค๐™ฃ๐™จ๐™ค๐™ก๐™š.๐™ก๐™ค๐™œ("๐˜ฟ๐™ž๐™ซ ๐™˜๐™ก๐™ž๐™˜๐™ ๐™š๐™™")>
 <๐™—๐™ช๐™ฉ๐™ฉ๐™ค๐™ฃ ๐™ค๐™ฃ๐˜พ๐™ก๐™ž๐™˜๐™ ={() => ๐™˜๐™ค๐™ฃ๐™จ๐™ค๐™ก๐™š.๐™ก๐™ค๐™œ("๐˜ฝ๐™ช๐™ฉ๐™ฉ๐™ค๐™ฃ ๐™˜๐™ก๐™ž๐™˜๐™ ๐™š๐™™")}>๐˜พ๐™ก๐™ž๐™˜๐™  ๐™ข๐™š</๐™—๐™ช๐™ฉ๐™ฉ๐™ค๐™ฃ> 
</๐™™๐™ž๐™ซ>
If you click the button, both logs will show:
๐˜ฝ๐™ช๐™ฉ๐™ฉ๐™ค๐™ฃ ๐™˜๐™ก๐™ž๐™˜๐™ ๐™š๐™™
๐˜ฟ๐™ž๐™ซ ๐™˜๐™ก๐™ž๐™˜๐™ ๐™š๐™™

This happens Because the event bubbles up from the button to its parent div, clicking a child element can trigger the parent's event too. ๐ŸงจHow to Stop Event Bubbling When you don't want the event to reach the parent. In that case, use:

๐™ค๐™ฃ๐˜พ๐™ก๐™ž๐™˜๐™ ={(๐™š) => { ๐™š.๐™จ๐™ฉ๐™ค๐™ฅ๐™‹๐™ง๐™ค๐™ฅ๐™–๐™œ๐™–๐™ฉ๐™ž๐™ค๐™ฃ(); ๐™˜๐™ค๐™ฃ๐™จ๐™ค๐™ก๐™š.๐™ก๐™ค๐™œ("๐˜ฝ๐™ช๐™ฉ๐™ฉ๐™ค๐™ฃ ๐™˜๐™ก๐™ž๐™˜๐™ ๐™š๐™™ ๐™ค๐™ฃ๐™ก๐™ฎ"); }}

Now, clicking the button won't trigger the parent's onClick handler. In an attempt to keep my writing short I'll just give a summary of the benefit of event bubbling:

๐ŸงจEvent bubbling helps you write less code: you can use one one event listener to trigger multiple events

๐Ÿงจimprove performance: Fewer event listeners mean less memory usage and faster event processing

I hope this was as fun to read as it was to write ๐Ÿฅธ