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
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() {
...
}
...
..
.
}
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)}>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With