ArticleZip > Example For Bubbling And Capturing In React Js

Example For Bubbling And Capturing In React Js

Bubbling and capturing are essential concepts in React.js that help manage events effectively within your application. Understanding how these mechanisms work can significantly enhance your ability to handle events and build a more interactive and responsive user interface.

When an event occurs in a React component, such as a button click or a key press, it triggers an event object that contains information about the event. Bubbling and capturing refer to how the event propagates through the component hierarchy.

Bubbling is the default behavior in React, where the event first triggers on the innermost component and then bubbles up through its ancestors. This means that if you have nested components and an event occurs in the innermost component, it will also trigger the same event in its parent component, and so on until it reaches the root component.

Capturing, on the other hand, involves capturing the event during the "capture" phase before it reaches the target element. Capturing allows you to handle the event at an earlier stage in the event propagation process. In React, capturing is less commonly used than bubbling but can be useful in certain scenarios where you need to intercept events before they reach their target.

To implement bubbling and capturing in React, you can use the `addEventListener` method to register event handlers with the respective phases. The `addEventListener` method takes three arguments: the event type, the event handler function, and a boolean value to indicate whether to use capturing (true) or bubbling (false).

Here's an example to demonstrate how you can use bubbling and capturing in React:

Jsx

import React from 'react';

function handleClick(event) {
  console.log('Clicked!', event.target);
}

function ExampleComponent() {
  return (
    <div>
      <h1>Example Component</h1>
      <button>Click Me</button>
    </div>
  );
}

export default ExampleComponent;

In this example, the `handleClick` function is triggered when the `

` element or the `
×