Mar 10, 2023 - 5 min read
When working with React, understanding how events propagate through the DOM is crucial for building interactive and responsive user interfaces. Two key concepts in event propagation are event capturing and event bubbling. In this blog post, we'll explore these concepts and how they work in React.
Event bubbling is the default behavior in most browsers. When an event occurs on an element, it first triggers the event handlers on that element, then moves up the DOM tree, triggering event handlers on its ancestors.
1import React from "react";
2const BubblingExample = () => {
3 const handleParentClick = () => {
4 alert("Parent clicked!");
5 };
6 const handleChildClick = () => {
7 alert("Child clicked!");
8 };
9 return (
10 <div
11 onClick={handleParentClick}
12 style={{ padding: "20px", backgroundColor: "#f0f0f0" }}
13 >
14 <div
15 onClick={handleChildClick}
16 style={{ padding: "20px", backgroundColor: "#d0d0d0" }}
17 >
18 Click me!
19 </div>
20 </div>
21 );
22};
23export default BubblingExample;
In this example, clicking on the child div will trigger the handleChildClick event handler first, followed by the handleParentClick event handler due to event bubbling.
Event capturing, also known as trickling is the opposite of event bubbling. In the capturing phase, the event starts from the root and travels down to the target element. To use event capturing in React, you can add the capture keyword to the event handler.
1import React from "react";
2const CapturingExample = () => {
3 const handleParentClickCapture = () => {
4 alert("Parent capture clicked!");
5 };
6 const handleChildClickCapture = () => {
7 alert("Child capture clicked!");
8 };
9 return (
10 <div
11 onClickCapture={handleParentClickCapture}
12 style={{ padding: "20px", backgroundColor: "#f0f0f0" }}
13 >
14 <div
15 onClickCapture={handleChildClickCapture}
16 style={{ padding: "20px", backgroundColor: "#d0d0d0" }}
17 >
18 Click me!
19 </div>
20 </div>
21 );
22};
23export default CapturingExample;
In this example, clicking on the child div will trigger the handleParentClickCapture event handler first, followed by the handleChildClickCapture event handler due to event capturing.
1import React from "react";
2const StopPropagationExample = () => {
3 const handleParentClick = () => {
4 alert("Parent clicked!");
5 };
6 const handleChildClick = (e) => {
7 e.stopPropagation();
8 alert("Child clicked!");
9 };
10 return (
11 <div
12 onClick={handleParentClick}
13 style={{ padding: "20px", backgroundColor: "#f0f0f0" }}
14 >
15 <div
16 onClick={handleChildClick}
17 style={{ padding: "20px", backgroundColor: "#d0d0d0" }}
18 >
19 Click me!
20 </div>
21 </div>
22 );
23};
24export default StopPropagationExample;
In this example, clicking on the child div will trigger the handleChildClick event handler and stop the event from propagating to the parent div.