The callback function is passed as an argument to another function.This allows data or functionality to be passed indirectly to the receiving function.As a result of its event-driven nature, this pattern is suitable for asynchronous and event-driven programming.Using callbacks, you can pass data from a child component to a parent component in JavaScript
The following steps will guide you through passing data via callbacks:
Parent Component
Create a callback function for receiving the data from the child.In this function, the data is passed as an argument and actions are performed (e.g., updating the parent state, triggering other actions).Child Component
Callback functions are provided as props to child components. You can name this prop anything you wish (e.g., onDataChange, sendData).In order to send data to the parent, you must call the callback function that was passed as a prop.You can pass the data you want to send to the callback function as an argument.The following example illustrates how you can accomplish this:
ParentComponent.js
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const [childData, setChildData] = useState(null);
// Callback function to receive data from child
const handleChildData = (data) => {
setChildData(data);
};
const parentClick = () => {
alert('Clicked in parent');
};
return (
<div>
<p>Data received from child: {childData}</p>
{/* Pass callback function as prop */}
<ChildComponent sendData={handleChildData} pclick ={parentClick}/>
</div>
);
}
export default ParentComponent;
ChildComponent.js
import React, { useState } from 'react';
const ChildComponent = ({ sendData, pclick }) => {
const [inputValue, setInputValue] = useState('');
const handleChange = (event) => {
setInputValue(event.target.value);
};
const handleClick = () => {
// Call the callback function and pass data to parent
sendData(inputValue);
};
return (
<div>
<input type="text" value={inputValue} onChange={handleChange} />
<button onClick={handleClick}>Send Data</button>
<button onClick={pclick}>p Data</button>
</div>
);
}
export default Child;