What does 'this.handleClick = this.handleClick.bind(this)' exactly do?

Tell us what’s happening:
Hello,

I’m a bit confused about what is the the purpose of this binding function, this.handleClick = this.handleClick.bind(this), in here?

Why do we need to mention handleClick on both left and right sides as well as what does bind() do here?

Your code so far


class MyComponent extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    name: 'Initial State'
  };
  this.handleClick = this.handleClick.bind(this);
}
handleClick() {
  // change code below this line
  this.setState({
    name: 'React Rocks!'
  });
  // change code above this line
}
render() {
  return (
    <div>
      <button onClick={this.handleClick}>Click Me</button>
      <h1>{this.state.name}</h1>
    </div>
  );
}
};

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36.

Challenge: Set State with this.setState

Link to the challenge:

2 Likes

When you’re passing onClick handler you’re changing context from your component to a button element, meaning when your handler will be invoked this will refer to a button which in turn doesn’t have .setState method you will try to call. In order to fix it you basically have two options:

  1. Explicetely bind this inside method to your component
  2. Use class fields creating methods with arrow function:
class MyComponent extends React.Component {
  state = {
    name: 'Initial State'
  };

  handleClick = () => {
    this.setState({
      name: 'React Rocks!'
    });
  };

  render() { /* As usual */  }
}

Arrow function does not have concept of this and this inside arrow function always refers to outer context at declaration time, which will always be your component (exactly what you need).

You’re rewriting your method on every contruction event (when constructor is invoked). It’s nothing different than this:

a = a.concat(b);

You can learn about .bind() here: Function.prototype.bind() - JavaScript | MDN

3 Likes

Thank you!

Best regards,
Konstantin

Keep in mind that both approaches considered to be anti-pattern (bad practice) and it’s one of the reasons why React components should be just functions.

1 Like

In my opininion, I think that if you don’t use this.handleClick = this.handleClick.bind(this) in React Class Component it cannot understand what to do when it doesn’t realize that where did you take the {this.handleClick} that you put it in your function. It seems like this is just another way to declare your variables.This is just what I thought!