/To pass data from child to parent component in React:
//Pass a function as a prop to the Child component.
//Call the function in the Child component and pass the data as arguments.
//Access the data in the function in the Parent.
/* Parent */
// The Parent creates the function to be used by the Child and
// whenever the Child calls the function, it is triggered from
// the Parent.
const Parent = () => {
const saveProjectFunction = data => {
// Recieving data(object) from the Child, instead of passing
// the object to the Child.
const modData = {
id: 1,
...data
}
console.log(`From the Parent ${modData}`);
}
return(
<Child onSaveProject={saveProjectFunction}/>
)
}
// NOTE: YOU CAN'T SKIP INTERMEDIATE COMPONENT
// The way you pass down through each component, is the same way
// You pass up without skipping a component
/* Child */
// The child basically calls the function from the parent which was
// pass in as props, but the function lives and is being used in
// the parent.
const Child = ({ onSaveProject }) => {
const sendData = () => {
const data = {
name: "kouqhar",
sport: "basketball"
}
// Sending the created data(object) to the Parent instead of
// Recieving data from the Parent.
onSaveProject(data)
}
return(
<button onClick={sendData}><button/>
)
}
// With love @kouqhar