Example for Bubbling and Capturing in React.js
Asked Answered
J

1

62

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?

Jeopardize answered 30/12, 2015 at 4:32 Comment(2)
event bubbling is a DOM specific event concept. The whole point of React is to get away from the DOM. You would do this in React by creating component functions and passing them down to children via propsSecondhand
Look at React events and React DOM event listenersZiguard
I
132

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

Iconoduly answered 30/12, 2015 at 5:55 Comment(8)
What is to keep in mind, all vanilla javascript events, for example from a library, are called beforehand. No matter if you register the event on Capture or Bubble phase.Amye
What if I want the opposite ? What if I am having the onClick for the parent and I want to call that function even when child is clicked ?Ethelinda
@Ethelinda That is normal event bubbling, as described in the first of the two examples above (the parent div's onClick is triggered when you click on the child button).Iconoduly
@MichelleTilley. Can you please help me here - #47691186Thibeault
@Amye that's very relevant - I've just extended your JSBin to reflect that jsbin.com/zuleceg/1Nevernever
What about with keydown? @MichelleTilleyCryptozoite
@Cryptozoite What about it? If you have a specific question that can't be answered in a small comment, please ask a separate SO question.Iconoduly
What are the use cases for capture phase event handlers?Winegar

© 2022 - 2024 — McMap. All rights reserved.