Home > OS >  object didnt get passed to another method (React)
object didnt get passed to another method (React)

Time:11-27

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)}

CodePudding user response:

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 })}

CodePudding user response:

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.

  • Related