object didnt get passed to another method (React)

I currently learning react and following a Video tutorial, and I get stuck with an object that can't be passed to another method but when i passed an ID it works fine

here's the method

handleIncrement = (product) => {
    console.log(product);
    this.setState({ count: this.state.count + 1 });   
};

and this is the method I try to pass on

render() {
    return (
      <div>
        <span className={this.getBadgeClasses()}>{this.formatCount()}</span>
        <button
          onClick={this.handleIncrement({ id: 1 })}
          className="btn btn-secondary btn-sm"
        >
          Increment
        </button>
      </div>
    );

the product on onClick={this.handleIncrement(product)} error as undefined

src\components\counter.jsx
  Line 19:47:  'product' is not defined  no-undef

but if i use onClick={() => this.handleIncrement({ id:1 })} it working just fine, and also work when i use onClick={(product) => this.handleIncrement(product)}

2 answers

  • answered 2021-11-27 10:16 Toivo Säwén

    The onClick event handler must be a function, not a function call. That's why the example you provided onClick={() => this.handleIncrement({ id:1 })} works as this is an anonymous function, while the example where you are calling the function does not work.

  • answered 2021-11-27 10:40 Isaac

    The problem that you have is with

    onClick={this.handleIncrement({ id: 1 })}
    

    This is the usual confusion to newbie in ReactJS but here is the general rule of thumb, you have two ways

    1. If your function is not expecting parameter
    funcWithoutParam = () => {
      console.log('hi')
    }; 
    onClick={this.funcWithoutParam}
    
    1. If your function is expecting parameter
    handleIncrement = (param) => {
      console.log(param)
    }
    
    onClick={() => this.handleIncrement({ id: 1 })}
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum