Los datos de los niños a los padres que pasan en React
Following are the steps to pass data from child component to parent component:
-In the parent component, create a callback function.
-This callback function will retrieve the data from the child component.
-Pass the cb function to the child as a props from the parent component.
-The child component calls the parent callback function using
props and passes the data to the parent component.
// example :
// step 1::
//->Parent component
//-> Create a callback function in Parent component.
import Child from './components/Child';
function App() {
const alertFunc = (data) => {
alert(data)
}
return (
// step 2:: Pass the cb function to the child component as a props.
<Child newFunc={alertFunc} />
);
}
export default App;
// step 3::
const Child = (props) => {
// Data in child component
const data = "HEY abi"
return (<>
<h1>{props.data}</h1>
//step 4::The child component calls the parent cb function using props
<button onClick={() => props.newFunc(data)}>Click Me</button>
</>);
}
export default Child;
Abhishek