What does bind do in this statement this.tick.bind(this) in the following code:
export class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {count: props.initialCount};
}
tick() {
this.setState({count: this.state.count + 1});
}
render() {
return (
<div onClick={this.tick.bind(this)}>
Clicks: {this.state.count}
</div>
);
}
}
The code is taken from the React site.
When we bind the this of the event handler to the component instance in the constructor, we can pass it as a callback without worrying about it losing its context. Arrow functions are exempt from this behavior because they use lexical this binding which automatically binds them to the scope they are defined in.
JavaScript Function bind() With the bind() method, an object can borrow a method from another object. The example below creates 2 objects (person and member).
To bind event handlers in React, the simplest, and the efficient way is to bind with arrow functions. Since this a new feature, it is not uncommon to see a lot of code using the binding in the constructor method. This is an equally efficient option to use.
Basically, bind allow you to stick a function to a given context. It's allow you to access to values stored in a specific Scope, in ReactJs the constructor scope generally. You can read that also, a great article passing in review the bind method.
.bind()
sets the this
of the function it is used to create, to be whatever parameter is passed in. Docs here.
In this case, it sets the this
of the tick()
function to be the render()
function's context.
You would do this because when a function is used as a DOM event handler, the this
is set to be the element that dispatched the DOM event. You want to guarantee that the this
is the one you expect, since it's used in tick()
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