Bind 'this' to a Class Method

Bind 'this' to a Class Method
0.0 0

#1

I don’t know what went wrong. I’m not able to click the “run test” button

Your code so far


class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      itemCount: 0
    };
    // change code below this line
    this.addItem() = this.addItem.bind(this);
    // change code above this line
  }
  addItem() {
    this.setState({
      itemCount: this.state.itemCount + 1
    });
  }
  render() {
    return (
      <div>
        { /* change code below this line */ }
        <button onClick={this.addItem}>Click Me</button>
        { /* change code above this line */ }
        <h1>Current Item Count: {this.state.itemCount}</h1>
      </div>
    );
  }
};

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/front-end-libraries/react/bind-this-to-a-class-method/


#2

You should not have () after this.addItem. You can not assign something to a function which is being executed, which is what tries to happen with the () being to the right of this.addItem.


#3

Ohh !!! I missed it.

Thanks a lot for your help :slight_smile: