There are two ways you can bind functions in React:
- one option is inside the constructor of the class component
- the other is works implicitly by using ES6 arrow functions
class MyComponent extends React.Component {
constructor(props) {
super(props)
}
handleClick = () => { ... }
}
or
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this);
}
handleClick() { ... }
}
The performance of both implementation is identical since the second implementation is compiled to the first one.
Understanding the .bind() method
Let’s try to understand the .bind() implicit method:
- this.handleClick = this.handleClick.bind(this); – First this.handleClick refers to the handleClick() method defined in the class – this refers to MyComponent
- this.handleClick = this.handleClick.bind(this); – Second this.handleClick is the same handleClick() method and we call the implicit .bind() method
- this.handleClick = this.handleClick.bind(this); – The last this is where we pass the context to .bind() and refers to MyComponent context
This will allow you to move the context of the handleClick to the component and be able to update the state: