Categories
React Answers

How to Add Event Bubbling and Capturing in React?

Spread the love

Sometimes, we want to add event bubbling and capturing in React.

In this article, we’ll look at how to add event bubbling and capturing in React.

Add Event Bubbling and Capturing in React

To add event bubbling and capturing in React, we can add event handlers to handle them.

To handle bubbling, we just add the regular event handlers.

And to handle capturing, we add Capture to the prop name after the event handler’s prop name.

For instance, we add bubbling by writing:

import React from "react";

export default function App() {
  return (
    <div onClick={() => console.log("parent")}>
      <button onClick={() => console.log("child")}>Click me</button>
    </div>
  );
}

We set the onClick prop of the parent div and the button to log 'parent' and 'child' respectively.

Then when we click the button, we see:

child 
parent 

logged in this order.

So we know event bubbling happened since we child element’s event handler is triggered before the parent’s.

To set event propagation to capturing mode, we add Capture to the end of each prop name.

For instance, we write:

import React from "react";

export default function App() {
  return (
    <div onClickCapture={() => console.log("parent")}>
      <button onClickCapture={() => console.log("child")}>Click me</button>
    </div>
  );
}

to set the onClickCapture prop instead of the onClick prop on each element.

Then we see:

parent 
child 

logged in this order.

So we know event capturing happened since we parent element’s event handler is triggered before the child’s.

Conclusion

To add event bubbling and capturing in React, we can add event handlers to handle them.

To handle bubbling, we just add the regular event handlers.

And to handle capturing, we add Capture to the prop name after the event handler’s prop name.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *