[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:
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
- Capturing phase came before bubbling phase.
- Event target and currentTarget seem to be the same (assumption at this point).
Clicking ‘Child’ text
- Capturing phase came before bubbling phase (same result as above).
- Capturing occurred as traversing
downthrough the DOM elements (going from parent to child).
- Bubbling occurred as traversing
upthrough the DOM elements(going from child to parent).
targetrefers to the (most deeply nested) element that triggered the event and
currentTargetrefers to the element handling the event.
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.targetto all the way up.
- In React, event handlers for the capturing phase can be registered by appending
Captureto the event name (onClick vs. onClickCapture).
event.targetis the inner most element that triggered the event and
event.currentTargetis the element handling the event.
- Event propagation can be stopped from capturing and bubbling by adding
So at this point, looking at the diagram below will make sense.
SyntheticEvent - React
This reference guide documents the SyntheticEvent wrapper that forms part of React's Event System. See the Handling…