How would you pass data from child to parent component in React?
How would you pass data from child to parent component in React?
To pass data from a child component to a parent component in React, you typically use a callback function approach. Here's a step-by-step explanation of how this can be implemented:
Define a Callback Function in the Parent Component: Start by creating a function in the parent component that is designed to handle the data coming from the child component. This function will typically update the state of the parent component based on the data received.
function ParentComponent() {
const [data, setData] = useState('');
const handleDataFromChild = (childData) => {
setData(childData);
};
return (
<div>
<ChildComponent sendDataToParent={handleDataFromChild} />
<p>Data from child: {data}</p>
</div>
);
}
Pass the Callback Function as a Prop to the Child Component: The next step is to pass this callback function as a prop to the child component. This allows the child component to call this function and send data back to the parent.
function ChildComponent({ sendDataToParent }) {
const someData = "Data from Child";
return (
<button onClick={() => sendDataToParent(someData)}>Send Data to Parent</button>
);
}
Invoke the Callback Function from the Child Component: Within the child component, you can invoke the passed call...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào