Peekay
Peekay

Reputation: 451

Callback function from child component in react

Here i have the parent child communication which works fine.

 var ParentComponent = React.createClass({
        update: function() {
            console.log("updated!");
        },
        render: function() {
          <ChildComponent callBack={this.update} />
        }
    })

    var ChildComponent = React.createClass({
    preupdate: function() {
        console.log("pre update done!");
    },
    render: function() {
      <button onClick={this.props.callback}>click to update parent</button>
    }
})

How shall i call the preupdate function in child component before calling the parent callback method during button Onclick event.

Upvotes: 3

Views: 16866

Answers (3)

Maheshvirus
Maheshvirus

Reputation: 7523

For react hooks can refer below solution.

  • ParentClass

    function ProfilePage() {
    
    const successCallBackData = (data) => {
       console.log(data)// can get callback data here
    }
    return (
        <>
          <AlertModal callBack={successCallBackData} /> 
        </>
    );
    }
    
    export default ProfilePage;
    
  • ChildClass

    const AlertModal = (props) =>{
    
    const goBack = () => {
        props.callBack('hello');// can pass callback data here
    }
    return (
        <>
          <div>
          <Button className="btn-round" color="danger"   onClick={goBack}>
            Go Back
                </Button>
          </div>
        </>
    );
    }
    
    export default AlertModal;
    

Upvotes: 2

the_cheff
the_cheff

Reputation: 5040

You could call the preupdate function as the click handler. Then when it is done it can invoke the callback.

var ParentComponent = React.createClass({
    update: function() {
        console.log("updated!");
    },
    render: function() {
      <ChildComponent callBack={this.update} />
    }
})

var ChildComponent = React.createClass({
    preupdate: function() {
        console.log("pre update done!");
        this.props.callback()
    },
    render: function() {
        <button onClick={this.preupdate.bind(this)}>click to update parent</button>
    }
})

Upvotes: 3

Chetan Jadhav CD
Chetan Jadhav CD

Reputation: 1146

Use the following:

<button onClick={(args)=>{this.preupdate(args);this.props.callback(args);}>click to update parent</button>

You'll also need to redefine the preupdate function like so:

preupdate: ()=> {
        console.log("pre update done!");
    }

so that you retain the this context while making a call to this method.

Upvotes: 0

Related Questions