Event Propagation in React: Capturing & Bubbling

Event Propagation in React: Capturing & Bubbling

Event propagation in React follows the standard DOM event flow, which consists of two phases: capturing and bubbling.

Capturing Phase

- The event travels from the root element down to the target element.
- In React, you can use the onClickCapture event to listen for events in the capturing phase.

Bubbling Phase

- The event bubbles up from the target element to the root.
- React’s normal event handlers, like onClick, are triggered in the bubbling phase.

Example Code

    
function EventPropagationExample() {
  const handleCapture = () => {
    console.log("Capturing Phase: Parent");
  };
  
  const handleBubble = () => {
    console.log("Bubbling Phase: Child");
  };
  
  return (
    
); }

Stopping Event Propagation

- Use event.stopPropagation() to prevent bubbling.
- Use event.preventDefault() to prevent the default action of the event.

Interactive Example