How to pass data from child component to its parent in ReactJS

codamint

Codamint

Posted on April 27, 2024

How to pass data from child component to its parent in ReactJS

Lifting the state up is the process by which React passes data from child to parent components. Following are the steps to pass data from the child component to the parent component:

  1. Define State in Parent Component: Specify the state that you like to be updated in the parent component in response to an action taken by the child component.
  2. Callback Function Pass Down: As a prop, a callback function is sent down from the parent component to the child component.
  3. Callback Invocation in Child Component: In the child component, call the callback function that was sent down from the parent component with the appropriate data to be delivered in response to the desired action (such as a button click).

Here's a simple example to help you understand this:

ParentComponent.js:

import { useState } from 'react';
import ChildComponent from './Child';

const ParentComponent = () => {
  const [dataFromChild, setDataFromChild] = useState('');

  const handleDataFromChild = (data) => {
    setDataFromChild(data);
  };

  return (
    <div>
      <h1>Data from Child: {dataFromChild}</h1>
      <ChildComponent sendDataToParent={handleDataFromChild} />
    </div>
  );
};

export default ParentComponent;
Enter fullscreen mode Exit fullscreen mode

ChildComponent.js:

const ChildComponent = ({ sendDataToParent }) => {
  const sendData = () => {
    const data = 'Data sent from child';
    sendDataToParent(data);
  };

  return (
    <div>
      <button onClick={sendData}>Send Data to Parent</button>
    </div>
  );
};

export default ChildComponent;
Enter fullscreen mode Exit fullscreen mode

In this case, clicking the button in the ChildComponent initiates the sendData method, which in turn calls the sendDataToParent callback function, which receives the data you wish to transfer ('Data sent from kid') from the parent component. Following that, the handleDataFromChild function within the parent component is called for, As a result updating the state with the data obtained from the child component.

💖 💪 🙅 🚩
codamint
Codamint

Posted on April 27, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related