2

By default event of element are in the bubbling phase. in javascript if we going to convert it to capture, we have the following way:

1- when the value of useCapture is set to true, the event uses the capturing propagation(in third argument):

element.addEventListener(event, function, useCapture);

2- jQuery only uses event bubbling.

now my main question is that although we make the evnet inline <div onclick= {} /> , how to change bubbling phase to capturing in React?

2 Answers2

2

This is quite straightforward.

For event bubbling

<div onClick={() => { alert('Bubbling');}} >
This will result into event bubbling
</div>

For event capturing

<div onClickCapture={() => { alert('Capturing');}} >
This will result into event capturing
</div>

You can also refer to the official docs here

Ayushya
  • 1,862
  • 1
  • 10
  • 15
1
 useEffect(() => {
    const handler = (event) => {
      //  write event handling logic here
    };
    // this will detect all clicks events
    document.addEventListener("click", handler, true);
    return () => {
      document.removeEventListener("click", handler);
    };
    // if we had a dependency, cleanup would be called before rerendering
  }, []);

assume that you have a button element in jsx

 <Button
    onClick={handleClick}
  >
    Test Button
  </Button>

when a user clicks on this button since we added true option for the registered event inside the useEffect, the browser will look at the top parent element which is the document, and starting from the top it will check if any parent has a click handler if it does it calls that first.

I explained in details here: What is event bubbling and capturing?

Yilmaz
  • 35,338
  • 10
  • 157
  • 202