wonderful world
wonderful world

Reputation: 11599

What does bind do in this react example?

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.

Upvotes: 6

Views: 5091

Answers (2)

Oakley
Oakley

Reputation: 666

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

Upvotes: 14

Hatem Jaber
Hatem Jaber

Reputation: 2402

It's used to pass arguments to the tick() method, it's just Javascript and nothing that is react specific.

Upvotes: 0

Related Questions