I am looking for an example in handling Bubbling and Capturing in React.js. I found one with JavaScript, but I am having trouble finding the equivalent for React.js.
How would I have to create an example for Bubbling and Capturing in React.js?
🟢 Capturing Phase – The is first phase when an event is actually triggered. This event “captures” or propagates first through the topmost event, that is the window object, then the document , then the html element, and then the innermost elements. It goes down until it reaches the event.
Event bubbling in React refers to when the innermost component handles an event, and events bubble outwards. In React, the innermost element will first be able to handle the event, and then surrounding elements will then be able to handle it themselves.
The event propagation mode determines in which order the elements receive the event. With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements. With capturing, the event is first captured by the outermost element and propagated to the inner elements.
Event bubbling is a method of event propagation in the HTML DOM API when an event is in an element inside another element, and both elements have registered a handle to that event. It is a process that starts with the element that triggered the event and then bubbles up to the containing elements in the hierarchy.
Bubbling and capturing are both supported by React in the same way as described by the DOM spec, except for how you go about attaching handlers.
Bubbling is as straightforward as with the normal DOM API; simply attach a handler to an eventual parent of an element, and any events triggered on that element will bubble to the parent as long as it's not stopped via stopPropagation
along the way:
<div onClick={this.handleClick}> <button>Click me, and my parent's `onClick` will fire!</button> </div>
Capturing is just as straightforward, though it's mentioned only briefly in the docs. Simply add Capture
to the event handler property name. For example onClick
becomes onClickCapture
:
<div onClickCapture={this.handleClickViaCapturing}> <button onClick={this.handleClick}> Click me, and my parent's `onClickCapture` will fire *first*! </button> </div>
In this case, if handleClickViaCapturing
calls stopPropagation
on the event, the button's onClick
handler will not be called.
This JSBin should demonstrate how capturing, bubbling, and stopPropagation
works in React: https://jsbin.com/hilome/edit?js,output
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With