Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between `onScroll` and `onScrollCapture` in React?

What’s the difference between onScroll and onScrollCapture in React?

Not sure if this is a DOM or pure JS topic since I can’t find any resources about onScrollCapture.

const node = (
  <div onScrollCapture={handleScrollCapture} />
);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

onScrollCapture in React is the equivalent of doing addEventListener('scroll', listener, { capture: true }) in vanilla JS, which means the event will fire on ancestors (parents and grandparents) of the element before it fires on the element itself (the target).

Traditionally, when registering an event listener, you would just do addEventListener('event', listener) without the third argument (or onEvent={listener} in React), which means the event will:

  1. Fire on the target first, and then
  2. Fire on ancestor elements as it bubbles (assuming it bubbles at all).

Which is the reverse order of what you’d get with onEventCapture and its vanilla-JS equivalent.

More generally, all events go through three phases:

  1. Capturing, where you start at the root of the DOM tree and trace the path down to find the element that actually triggered the event (the target).
  2. Targeting, where the event fires on the target itself once it’s reached.
  3. Bubbling, where the event travels back up to the root of the DOM. (If and only if the event bubbles.)

For parent elements, events only fire in either the bubbling or capturing phase, not both, and when they fire is determined by:

  • Whether the event bubbles at all (some events don’t).
  • Whether you supplied the third argument to addEventListener.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading