React js - passing a function as prop and calling it onClick giving a type error

64 Views Asked by At

Hi I am trying to implement a add to Cart functionality where I am trying to pass a function as prop to the add to cart button

below is my function

 const handleAddToCart = async(productId,quantity) => 
    {
      const item = await commerce.cart.add(productId,quantity)
      setCart(item.cart)
    }

Below is the function having the button onClick Call

import React from 'react'


const Product = ({product, onAddToCart}) => {


        return(

            //Wrapping the image in a card
      
                      <div className="rounded overflow-hidden shadow-lg">
                          { <img className= "object-contain h-20 w-20" 
                               src={product.image.url} 
                               alt={product.name}
                          /> }
                          <div className="px-1 py-1">
                              <div className="text-s">{product.name}</div>
                          </div>

                          <button className="bg-grey-light hover:bg-grey text-grey-darkest font-bold py-2 px-4 rounded inline-flex items-center"
                                  onClick={() => onAddToCart(product.id, 1)}>
                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M24 3l-.743 2h-1.929l-3.474 12h-13.239l-4.615-11h16.812l-.564 2h-13.24l2.937 7h10.428l3.432-12h4.195zm-15.5 15c-.828 0-1.5.672-1.5 1.5 0 .829.672 1.5 1.5 1.5s1.5-.671 1.5-1.5c0-.828-.672-1.5-1.5-1.5zm6.9-7-1.9 7c-.828 0-1.5.671-1.5 1.5s.672 1.5 1.5 1.5 1.5-.671 1.5-1.5c0-.828-.672-1.5-1.5-1.5z "/></svg>
                          </button>

                      </div>
      
                  )

}

export default Product

Below is the map function that calls the above card

const ProductsContainer = ({products, onAddToCart}) => {


    return(
    
        <div className = "container mx-auto"> 
             <div className="grid grid-cols-3 gap-2 auto-rows-max">
             {/*Calling the Product card component to render the product details*/}

                {products.map((product) => { 
                 return <Product product = {product} key= {product.id} onAddToCart = {onAddToCart}/>
                })
             }
            </div>
        </div>
        
        )

}

export default ProductsContainer

And below is how i am calling it

 <ProductsContainer products = {products} onAddToCart = {handleAddToCart}/>

I am getting the below error

TypeError: onAddToCart is not a function

Please suggest

0

There are 0 best solutions below