React : Calling parent component method in child component

In my react app i am passing down my function reference to the child component using props onIncQty={this.handleIncreaseQty } . The function is declared as:

handleIncreaseQty = (product) => {
      const { products } = this.state;
      const index = products.indexOf(product);
      products[index].qty += 1
          products : products 
          //we could have written simple products too

Now in the child component there is an onClick event which calls the parent method. It is called as

 onClick={() => onIncQty(product)}

Now why are we using callback here when we are already binding the handleIncreaseQty function when declaring it. We could have simply written


but it does not work why is that? Do we need to bind it again? Because the following code also works:


Because event handlers in JS accept a function as an argument. This


Isn’t a function, it’s the result of calling a function: it’s a value. And the return value of that is undefined, so you’re just writing


You have to pass a function in, so like

onClick={() => onIncQty(product)}

bind is a method all functions in JS have that creates another function from the one you give it (one where you can set what the value of this is), which is why the second example works, although it’s much less clear what’s happening than just writing

onClick={() => onIncQty(product)}
1 Like

Thankyou for answering. That cleared my problem.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.