In React, bidirectional communication between parent and child components is typically achieved by passing callback functions from the parent to the child as props. These callback functions are then invoked by the child to send data or trigger actions in the parent component. Here’s an example:
// ParentComponent.js
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const [parentData, setParentData] = useState('');
const handleChildData = (data) => {
// Update parent component state with data from the child
setParentData(data);
};
const sendDataToChild = () => {
// Send data from the parent to the child
const dataToSend = 'Data from Parent';
// Invoke a function in the child component to send data
childRef.current.receiveDataFromParent(dataToSend);
};
return (
<div>
<p>Data from Child: {parentData}</p>
<button onClick={sendDataToChild}>Send Data to Child</button>
<ChildComponent onData={handleChildData} />
</div>
);
};
export default ParentComponent;
// ChildComponent.js
import React, { useState } from 'react';
const ChildComponent = ({ onData }) => {
const [childData, setChildData] = useState('');
const receiveDataFromParent = (data) => {
// Update child component state with data from the parent
setChildData(data);
};
const sendDataToParent = () => {
// Send data from the child to the parent using the callback function
onData(childData);
};
return (
<div>
<p>Data from Parent: {childData}</p>
<button onClick={sendDataToParent}>Send Data to Parent</button>
</div>
);
};
export default ChildComponent;
In this example:
- The
ParentComponent
has a state variableparentData
and a functionhandleChildData
that updates the state with data received from the child. - The
ChildComponent
receives a callback functiononData
as a prop. It also has a functionreceiveDataFromParent
that updates the child component state with data from the parent. The child can then invoke theonData
callback to send data back to the parent. - The
ParentComponent
renders theChildComponent
and provides thehandleChildData
callback as a prop. It also has a button that, when clicked, sends data from the parent to the child by calling a function in the child component (receiveDataFromParent
).
This pattern allows for bidirectional communication between parent and child components in React.
Show Comments