How to call method inside the same class in ReactJS?

Casper picture Casper · Jun 28, 2016 · Viewed 8.3k times · Source

I want to call the method inside the same class. For example, when I click a button, it will trigger the method handleLoginBtnClicked(). I expect it will call the method checkInputValidation() in the same class. What is the proper way to do this?

export default class LoginCard extends React.Component {

    //If I click a button, this method will be called.
    handleLoginBtnClicked() {
        this.checkInputValidation();
    }

    checkInputValidation() {
        alert("clicked");
    }
    ...
    ...
    ...
    render() {
        ...
        <LoginBtn onClick={this.handleLoginBtnClicked}/>
        ...
    }
}

Error Message:

Uncaught TypeError: this.checkInputValidation is not a function

Answer

Elod Szopos picture Elod Szopos · Jun 28, 2016

You will need to bind those functions to the context of the component. Inside constructor you will need to do this:

export default class LoginCard extends React.Component {
    constructor(props) {
        super(props);
        this.handleLoginBtnClicked = this.handleLoginBtnClicked.bind(this);
        this.checkInputValidation = this.checkInputValidation.bind(this);
    }

    //This is the method handleLoginBtnClicked
    handleLoginBtnClicked() {
        ...
    }

    //This is the method checkInputValidation 
    checkInputValidation() {
        ...
    }

    ...
    ..
    .
}