There are 3 possible ways to achieve,
- Binding in Constructor: In JavaScript classes, the methods are not bound by default. The same thing applies for ReactJS event handlers defined as class methods. Normally we bind them in constructor as follows,
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
// Perform some logic
}
- Public class fields syntax: If you don’t like to use bind approach then public class fields syntax can be used to correctly bind callbacks
handleClick = () => {
console.log('this is:', this);
}
<button onClick={this.handleClick}>
Click me
</button>
- Arrow functions in callbacks: You can use arrow functions directly in the callbacks as below
<button onClick={(e) => this.handleClick(e)}>
Click me
</button>