skip to Main Content

Good afternoon. There is a product card that is a link. On the card there is a button for adding a product, on which the onclick event is hung. When you click on the button, the card link is triggered. Tell me how to solve this problem.

<Link to={'Bigcard'} className="product__link">
      
    <div className="product__card">{props.count}
      <img className="product__img" src={props.url} alt="" />
      <h4 className="product__title">{props.title}</h4>
      <p className="product__description">{props.description}</p>
      <div className="product__parameters-button">
        
        <div className="product__parameters">
          <p className="product__price">{props.price} ₽</p>
          <p className="product__weight"> / {props.weight} г.</p>
        </div>
        
        <div className="product__plus" onClick={addProduct}>
          <img src={plus} alt="" className="product__plus-img" />
        </div>
        
      </div>
    </div>
    
    </Link>

2

Answers


  1. I think event.stopPropagation() will help you. This stops the control from inner div click to outer div. Also consider reading event.preventDefault() which prevents default functionality execution.
    Refer to the documentation here.

    Working example can be found at this link

    Login or Signup to reply.
  2. It seems like you set a link to the whole card, so something like this should work:

    <div className="product__card">{props.count}
      <img className="product__img" src={props.url} alt="" />
      <h4 className="product__title">{props.title}</h4>
      <p className="product__description">{props.description}</p>
    
      <Link to={'Bigcard'} className="product__link">
      <div className="product__parameters-button">
      </Link>
        
        <div className="product__parameters">
          <p className="product__price">{props.price} ₽</p>
          <p className="product__weight"> / {props.weight} г.</p>
        </div>
        
        <div className="product__plus" onClick={addProduct}>
          <img src={plus} alt="" className="product__plus-img" />
        </div>
        
      </div>
    </div>
    

    Now only the button triggers the link.
    You can also try event.preventDefault() or event.stopPropagation() as @Hamza Mushtaq said, setting a listener event in the card to check if he button was clicked.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search