Home > Net >  remove parents onclick function on child button
remove parents onclick function on child button

Time:02-03

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 :)

CodePudding user response:

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 !

CodePudding user response:

Yes, it is possible. To prevent the button from triggering the routing to the path, you can wrap the button in an anchor tag with href="#" and prevent the default behavior on the click event of the button. The code would look like this:

  • Related