Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call method inside the same class in ReactJS?

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
like image 456
Casper Avatar asked Jun 28 '16 16:06

Casper


2 Answers

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() {
        ...
    }

    ...
    ..
    .
}
like image 185
Elod Szopos Avatar answered Sep 29 '22 02:09

Elod Szopos


Where are you binding the handleLoginBtnClicked? You may be losing the functions context and losing the meaning of the special variable this. React will handle and trigger the onClick event, calling the function from a different context which is why it has been lost.

You should use the following syntax to create a new bound function to add as the event listener for the onClick event. This will ensure that handleLoginBtnClicked's context is not lost.

<element onClick={this.handleLoginBtnClicked.bind(this)}>
like image 23
bitten Avatar answered Sep 29 '22 00:09

bitten