0

here i have a button inside a div . i have wrapped the main div inside a Link tag , which means whenever i click anywhere inside the div it will route me to the path given. but i dont want that to be applied on my button. i want the button to perform entirely different function rather than routing when clicked? is than even possible ?

here's the code

<Link to={`/shop/${book.id}`}>
    <div className='book-card'>
        <img src={book.image} alt="" />
        <h3>{book.title}</h3>
        <div>
            <p>Rating :{book.rating}</p>
            <p>${book.price}</p>
        </div>
        <button onClick={()=> console.log('Clicked')}>Add To Cart</button>
    </div>
</Link>

thanks :)

  • 1
    Related: [https://stackoverflow.com/questions/5963669/whats-the-difference-between-event-stoppropagation-and-event-preventdefault](https://stackoverflow.com/questions/5963669/whats-the-difference-between-event-stoppropagation-and-event-preventdefault). Just stop the propagation of event in button onClick function – Sergey Sosunov Feb 03 '23 at 14:09
  • Does this answer your question? [How can I stop a child button triggering a parent Link in React?](https://stackoverflow.com/questions/67557185/how-can-i-stop-a-child-button-triggering-a-parent-link-in-react) – Sergey Sosunov Feb 03 '23 at 14:39

1 Answers1

0

Of course. It's possible.

This is bubbling concept. Using e.stopPropagation can perform it.

<button onClick={(e)=> { e.stopPropagation(); console.log('Clicked')}}>Add To Cart</button>

Ref: https://javascript.info/bubbling-and-capturing

Enjoy !

tanthuann
  • 1
  • 1
  • i dont know y but unfortunately `e.stopPropagation()` didnt worked. but `e.preventDefault()` did . can u explain? – Hamdan Salih Feb 03 '23 at 14:19
  • Sorry for my mistake. If you use Link component (a tag), it triggers changing to URL, stop the propagation of event isn't work with href attibute. You should call e.preventDefault() in onClick at Link component. Thanks. – tanthuann Feb 03 '23 at 14:34