Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does bind do in this react example?

Tags:

reactjs

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.

like image 793
wonderful world Avatar asked Aug 20 '15 17:08

wonderful world


People also ask

Why do we need to bind this in React?

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.

What is bind () in JS?

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).

How do you bind events in React?

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.

What is BIND In React native?

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.


1 Answers

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

like image 68
Oakley Avatar answered Oct 05 '22 19:10

Oakley