Skip to content

Event Propagation in React

Published:

In reality Event Propagation concept is quite easy, but people tend to throw lots of words like, “Bubbling”, “Capturing”, “Delegations” “Events going up”, “Events going down” those terms confuses people, yet they all true in their own terms. Event propagation in React works just like in real DOM, but events wrapped up in SyntheticEvents. But that doesn’t change anything, they still behave as if they are working on DOM. So learning this concept in React pretty much appliable to anywhere where the DOM exists, at least some form of it.

Imagine a scenario where you have to click item inside another item. Can you do this without invoking wrapper elements click handler? No, you can’t because, that is fundamentally impossible. Even though we think we clicked on the most inner item we are still interacting with parent or wrapper element one way or another. So, this is where the stopPropagation() comes in. Whenever an event tries to go up or down in the DOM tree, calling stopPropagation() will prevent that to happen. So, events can only propagate - moves up or down - till we prevent it.

Now, we try to emphasize those buzz-words one by one starting off with Bubbling.

Bubbling

🔗Event Bubbling’s Github address

Bubbling means events going upwards. If you go ahead and click on LEVEL 3 it still says you clicked on LEVEL 1. But, how, you just clicked on most inner div right? That is because, in their default state events tries to propagate upwards on click.

Event Bubbling

But not to worry there is a really easy way to fix this in React.

const handleParentClick = (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
  event.stopPropagation();
  alert('LEVEL 1');
};
const handleFirstChildClick = (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
  event.stopPropagation();
  alert('LEVEL 2');
};
const handleSecondChildClick = (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
  event.stopPropagation();
  alert('LEVEL 3');
};

These are the event handlers we used in our example. All we did was adding a event.stopPropagation(). This makes sure event won’t propagate upwards. Now, if you go ahead click Stop Propagation checkbox, events won’t be able to propagate.

Event Bubbling Recap

Now that we get Bubbling out of the way. Proceeding to Capturing.

Capturing

🔗Event Capturing’s Github address

Capturing means events going downwards as oppose to Bubbling. This time, if we click on LEVEL 3 now it starts from the most outer to most inner. Just like bubbling but everything in reverse.

Event Capturing

To disable that all we need to use is event.stopPropagation(), again. People associate stopPropagation with only bubbling phase, but propagate means events moving through DOM elements without the direction matters - up or down -. If we go ahead and apply the same piece of code above, capturing will be prevented.

Event Capturing Recap