DEV Community

Paul Ikenna
Paul Ikenna

Posted on

Passing Data from a Child Component to a Parent Component

In Reacct, Passing Data from a child component to its parent is not that simple but can be achieveable through the use of callback function. This process is commonly referred to as lifting state up, where the parent component manages the state of its child components.

To pass data from a child component to parent component, you define a callback function in the parent component, pass it down to the child component as prop. The child component call this callback function and pass the data to it as argument.

// Parent component
import { useState } from 'react';
import ChildComponent from './ChildComponent';

const ParentComponent = () => {
  const [data, setData] = useState(null);

  const handleDataChange = (newData) => {
    setData(newData);
  };

  return (
    <div>
      <p>Data from child component: {data}</p>
      <ChildComponent onDataChanged={handleDataChange} />
    </div>
  );
}

// Child component
import { useState } from 'react';

const ChildComponent = (props) => {
  const [childData, setChildData] = useState(null);

  const handleButtonClick = () => {
    props.onDataChanged(childData);
  };

  return (
    <div>
      <input type="text" value={childData} onChange={(e) => setChildData(e.target.value)} />
      <button onClick={handleButtonClick}>Update parent</button>
    </div>
  );
}

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bkosalgc5jf3dcjihk5v.png)
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
ashcript profile image
As Manjaka Josvah

Can't we just pass the setData(...) function as a prop to the child component instead of using an intermediate function?

Collapse
 
ikechukwu411 profile image
Paul Ikenna

wow, this is so true..I never saw it that way.. Yes, it is possible to pass the setData function directly as a prop to the child component, without using an intermediate function. It makes the code more cleaner.. Thank You