Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react calling a function in a child component

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}
    } 
})
like image 617
chinds Avatar asked Feb 23 '16 11:02

chinds


1 Answers

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" />.

like image 178
David Avatar answered Sep 18 '22 22:09

David