React: Bind 'this' to a Class Method

Tell us what’s happening:

In this class component, how come the parentheses aren’t needed around the call of the function addItem()?

<button onClick={this.addItem}>Click Me</button>

I thought that in React JSX, anything inside { } should be regular Javascript expressions, and that in JS, you need to include parentheses ()when calling functions?

Thanks!

Complete code below:
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 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36.

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

1 Like

Hi @sidneyyin!

I suggest you read this post, I think it will clear your doubts!

Thanks - I’ll read more on it - React is still quite new to me and reading their documentation is still confusing. But I think the documentation is explaining that if this is binded (bound?), then you don’t need parentheses after the method call inside a JSX expression…

1 Like

@camperextraordinaire Out of curiosity, what would the syntax be to assign a function if you call it with arguments ie, how do you pass the params to the assignment?

The only parameter passed to the onClick method is a single event parameter, and there’s no way to change this. If you want to call another function with extra arguments, put that call in your addItem method.

Edit: Yikes, I forgot about using .bind to bind extra arguments. Thanks @camperextraordinaire for the tip :slight_smile: