skip to Main Content

When I click on the Link parent it fires the click on the button as well, I want both events to be separated.

<Link className="product-item__link" to={`/products/${product.category}/${product.id}`} >
    <div className='product-item'>
        {/*I have here other elements*/}
        <button className="product-item__btn" onClick={() => addToCart(product)}>Add to cart</button>
     </div>
</Link>

2

Answers


  1. Add stop propagation in the function call of button click

    <Link className="product-item__link" to={`/products/${product.category}/${product.id}`} >
        <div className='product-item'>
            {/*I have here other elements*/}
            <button className="product-item__btn" onClick={(e) => addToCart(e, product)}>Add to cart</button>
         </div>
    </Link>
    

    change function definition

    const addToCart = (e, product) => {
          e.stopPropagation();
          e.preventDefault();
          //rest of the code...
    }
    
    Login or Signup to reply.
  2. <Link className="product-item__link" to= 
    {`/products/${product.category}/${product.id}`}>
    <div className='product-item'>
    {/* Other elements */}
    <button className="product-item__btn" onClick={(event) => {
        event.stopPropagation(); // Stop the event propagation
        addToCart(product);
    }}>
      Add to cart
    </button>
    </div>
    </Link>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search