Reputation: 5123
function Parent({children}) {
// How does Parent pass in state to children
// And how does Parent get state from children?
return <div>{children}</div>
}
How does Parent pass in state to children? And how does Parent get state from children?
Upvotes: 0
Views: 24
Reputation: 1268
I've not tested it but the following should work AFAIK. Gist of it is that you can use React.cloneElement(...)
to inject the props
function Parent({children}) {
const someOtherProp = 'a prop value';
return <div>{
React.Children.map(
children,
child => React.cloneElement(child, {...child.props, someOtherProp})
);
}</div>
}
That'll let you pass state down to children. As for passing state back up you can't, however the general approach would be to store the state at this parent level and pass setter functions to the children (i.e. when the child calls setStateValue(...)
it's actually setting parent state).
Upvotes: 1