Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event propagation with React bubbling out of order

Given the following code I would expect a printout of 3, 2, 1 when clicking the number 3. Actual printout is 1, 3, 2.

What is the reason for this?

document.body.onclick = () => {
  console.log('1')
}

function Test() {
  return (
    <div onClick={() => console.log('2')}>
      2
      <div onClick={() => console.log('3')}>
        3
      </div>
    </div>
  )
}

ReactDOM.render(<Test/>, document.querySelector("#root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<body>
1
<div id="root" />
</body>
like image 693
mikabytes Avatar asked Jul 20 '17 11:07

mikabytes


People also ask

Does React use event bubbling?

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.

Which event can be used to stop event propagation in React?

stopPropagation() within a ReactJS component to stop a click event from bubbling up and triggering a click event that was attached with JQuery in legacy code, but it seems like React's stopPropagation() only stops propagation to events also attached in React, and JQuery's stopPropagation() doesn't stop propagation to ...

Does event capturing happen first or is it event bubbling?

Event capturing means propagation of event is done from ancestor elements to child element in the DOM while event bubbling means propagation is done from child element to ancestor elements in the DOM. The event capturing occurs followed by event bubbling.


1 Answers

Any native event handlers will fire before React event handlers.

This is how React works with events:

  1. It listens to events at the top-level and converts them to Synthetic Events
  2. Puts them in a pool to maintain order
  3. Dispatches to React components

Because of this, order is maintained within the React ecosystem but out of order relative to the rest.

As explained in this video: https://www.youtube.com/watch?v=dRo_egw7tBc

And vaguely described in the docs: https://facebook.github.io/react/docs/events.html#event-pooling

like image 135
mikabytes Avatar answered Oct 15 '22 10:10

mikabytes