Im trying to call a function that is stored in a child component form the parent. But not sure to to do it. I know if were form child to parent I could simply use the component props but not sure how to do it from parent to child.
as you can see form the below example the button in the parent class need to trigger the display function in the child class.
var Parent = React.createClass ({
render() {
<Button onClick={child.display} ?>
}
})
var Child = React.createClass ({
getInitialState () {
return {
display: true
};
},
display: function(){
this.setState({
display: !this.state.display
})
},
render() {
{this.state.display}
}
})
The easiest way to achieve this is through using refs
(See documentation).
var Parent = React.createClass ({
triggerChildDisplay: function() {
this.refs.child.display();
},
render() {
<Button onClick={this.triggerChildDisplay} />
}
})
var Child = React.createClass ({
getInitialState () {
return {
display: true
};
},
display: function(){
this.setState({
display: !this.state.display
})
},
render() {
{this.state.display}
}
})
I basically copied in your example, but do note that in your Parent, I don't see you render a Child component, but typically, you would, and on that Child you would give it a ref, like <Child ref="child" />
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With