How to bubble events through nested components in React?

Estimated read time 2 min read

In React, you can bubble events through nested components using callback functions. You can define a callback function in the parent component and pass it as a prop to the child component. The child component can then call the callback function with any event data as an argument, and the parent component can handle the event.

Here’s an example of how to bubble events through nested components in React:

import React from 'react';

function ChildComponent(props) {
  const { onClick } = props;

  const handleClick = () => {
    onClick('Hello from ChildComponent!');
  };

  return (
    <button onClick={handleClick}>Click me</button>
  );
}

function ParentComponent() {
  const handleChildClick = (data) => {
    console.log(data);
  };

  return (
    <div>
      <h1>ParentComponent</h1>
      <ChildComponent onClick={handleChildClick} />
    </div>
  );
}

export default ParentComponent;

In this example, we’re defining a ParentComponent that contains a callback function called handleChildClick. We’re passing the handleChildClick function as a prop called onClick to the ChildComponent.

In ChildComponent, we’re accessing the onClick prop and defining a handleClick function. We’re calling the onClick function with the string 'Hello from ChildComponent!' as an argument when the button is clicked.

When the button is clicked, the handleClick function is called and the onClick prop function in the ParentComponent is called with the string 'Hello from ChildComponent!' as an argument. We’re then logging the event data to the console.

By defining a callback function in the parent component and passing it as a prop to the child component, you can easily bubble events through nested components in React.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply