Bind 'this' to a Class Method - Episode IV

Bind 'this' to a Class Method - Episode IV
0

#1

Well, I’m convinced this is the right code, but it produces an error which I do not understand. The code should bind the ‘this’ keyword to the .addItem() method, making it available for use in the component. But I have no idea what this error means.

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 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36.

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


#2

You are executing the function instead of just passing the function.


#3

Ooooohhhhhhhh…Interesting.