const Parent = props => {
return <Child {...props} />
}
<Component propOne={propOne} propTwo={propTwo} {...props}>
{children}
</Component>
import React, { Children, isValidElement, cloneElement } from 'react';
const Child = ({ doSomething, value }) => (
<div onClick={() => doSomething(value)}>Click Me</div>
);
function Parent({ children }) {
function doSomething(value) {
console.log('doSomething called by child with value:', value);
}
render() {
const childrenWithProps = Children.map(children, child => {
// Checking isValidElement is the safe way and avoids a TS error too.
if (isValidElement(child)) {
return cloneElement(child, { doSomething })
}
return child;
});
return <div>{childrenWithProps}</div>
}
};
ReactDOM.render(
<Parent>
<Child value="1" />
<Child value="2" />
</Parent>,
document.getElementById('container')
);
/* 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