8

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
Casper
  • 4,435
  • 10
  • 41
  • 72

2 Answers2

8

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

    ...
    ..
    .
}
Casper
  • 4,435
  • 10
  • 41
  • 72
Elod Szopos
  • 3,475
  • 21
  • 32
  • Any reason you chose to not do this in the constructor? – lux Jun 28 '16 at 16:16
  • @CasperLI This would be one of the best practices that there are. For more information you can follow [the link here](http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html) – Elod Szopos Jun 28 '16 at 16:56
2

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)}>
bitten
  • 2,463
  • 2
  • 25
  • 44