In React, passing data from a child component to a parent component involves using callback functions. This is because data flow in React is generally unidirectional, from parent to child. However, you can still achieve child-to-parent communication by passing a function from the parent to the child as a prop, and the child can then call this function with the data it wants to pass back to the parent.

Here’s a step-by-step guide on how to pass data from a child component to a parent component in React:

  1. Define the Parent Component:
    In the parent component, create a function that will handle the data received from the child component. Pass this function to the child as a prop.
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';

const ParentComponent = () => {
  const [childData, setChildData] = useState('');

  const handleChildData = (data) => {
    // Update parent component's state with the data received from the child
    setChildData(data);
  };

  return (
    <div>
      <h1>Parent Component</h1>
      <ChildComponent onDataReceived={handleChildData} />
      <p>Received from child: {childData}</p>
    </div>
  );
};

export default ParentComponent;
  1. Create the Child Component:
    In the child component, receive the callback function as a prop and call it with the data you want to pass to the parent.
import React, { useState } from 'react';

const ChildComponent = ({ onDataReceived }) => {
  const [childInput, setChildInput] = useState('');

  const handleChange = (event) => {
    setChildInput(event.target.value);
  };

  const sendDataToParent = () => {
    // Call the parent's callback function with the child data
    onDataReceived(childInput);
  };

  return (
    <div>
      <h2>Child Component</h2>
      <input type="text" value={childInput} onChange={handleChange} />
      <button onClick={sendDataToParent}>Send Data to Parent</button>
    </div>
  );
};

export default ChildComponent;

In this example, the handleChildData function in the parent component is passed to the ChildComponent as a prop called onDataReceived. The child component uses this prop to call the function with the data it wants to pass back. When the button in the child component is clicked, the input data is sent to the parent component, where it updates the parent’s state and triggers a re-render.

This pattern allows you to achieve communication from child to parent in a controlled and organized manner within the React component hierarchy.

Leave a Reply

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