'html Button on top of link
Hey I have a div which is wrapped by a Link component, and inside that div I have more buttons, but the problem is, when I click on the inner smaller buttons, I actually click on the Link component as well, so I get redirected which is not what I want... How do I fix this?
it seems as though both the link and the button get clicked but if i am intending to click the button only i want to avoid the parent link.
What I mean is, the Link is used to navigate to some URL when you click on it. Putting elements inside that for other tasks. like a blog post, you click on the parent it will redirect you, but on the child the button will allow you to delete it
was coding this in nodejs react so i was using onClick events
example
<Link to="/blog-post">
<div className="link-post-container">
...blog
<button className='deleteButton'></button>
</div>
</Link>
I have tried event.stopPropagation
on the button but it still doesn't seem to do anything. Is it because the Link is an href
instead of a onClick
?
SOLUTION
so using some of the possible solutions below i started messing around and noticed by in the onClick of the deleteButton, if i add the following in, it works:
event.preventDefault()
with this, the redirect because of the href does not occur anymore and only the button click event will take place
Solution 1:[1]
const handleClick = event => {
event.stopPropagation()
// then write rest of your onclick code
}
<button className='deleteButton' onClick={handleClick}></button>
Solution 2:[2]
The click event propagates from the button upwards in the DOM tree until it reaches the root (simplified explanation - you can learn more about event propagation here). This is why the link also registers it and runs its onclick handler, redirecting you to another site.
You can call event.stopPropagation()
inside your button's onClick handler to stop the event from reaching the encapsulating link.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | SR Sajjad |
Solution 2 |