[React] Event Capturing and Event Bubbling

Imagine a component which has the following code:

This sample will render a ‘Parent’ text and a ‘Child’ text like this:

Rendered contents

How would the console output differ between clicking ‘Parent’ text versus ‘Child’ text? Let us analyze each output to learn about event propagation.

Clicking ‘Parent’ text

Observations:

  • Capturing phase came before bubbling phase.
  • Event target and currentTarget seem to be the same (assumption at this point).
Console output when ‘Parent’ text is clicked

Clicking ‘Child’ text

Observations:

  • Capturing phase came before bubbling phase (same result as above).
  • Capturing occurred as traversing down through the DOM elements (going from parent to child).
  • Bubbling occurred as traversing up through the DOM elements(going from child to parent).
  • Event target refers to the (most deeply nested) element that triggered the event and currentTarget refers to the element handling the event.
Console output when ‘Child’ text is clicked

Summary

Looking at this trivial example, there were a few takeaways.

  • Event propagation consists of event capturing and event bubbling. It starts with capturing phase and event captures down until it reaches event.target. Then, event bubbles up from event.target to all the way up.
  • In React, event handlers for the capturing phase can be registered by appending Capture to the event name (onClick vs. onClickCapture).
  • event.target is the inner most element that triggered the event and event.currentTarget is the element handling the event.
  • Event propagation can be stopped from capturing and bubbling by adding event.stopPropagation().

So at this point, looking at the diagram below will make sense.

https://developer.mozilla.org/ko/docs/Learn/JavaScript/Building_blocks/Events

Reference:

--

--

--

https://www.linkedin.com/in/jaesik-kim-706b4a84

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to build an Interstellar VR CommLink with Google Daydream and WebAudio

A Quick Demo How To Write Unit Test Calling Third-Party APIs With Sinon Mock In Node.JS

React Forms

Test REST APIs using Jest and Supertest

How to create an attractive person webpage within just 10 mins using HTML and CSS

Using ~ instead of .rawValue

The Prototype Inheritance in JavaScript is not an Accident

Step by step installation and configuration of ESLint and Prettier in Angular.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
J.Kim

J.Kim

https://www.linkedin.com/in/jaesik-kim-706b4a84

More from Medium

A Beginner’s Guide to Linked Lists

Introduction to mobx

Application frameworks on my point of view

Deep into the world of JavaScript and MongoDB