I have a card wrapped in a Link
from the react-router-dom@v5
. Inside the Link
is a div for the card and the div is positioned relatively. Inside the card div is an icon positioned absolutely to the card that when clicked should change background color. The problem now is that clicking on the icon also clicks the Link
which I don’t want. I tried to use e.preventDefault()
but it also stops all subsequent events from firing again properly as I want to be able to flip the background color of the icon any time I click on it. I tried e.stopPropagation()
and e.nativeEvent.stopImmediatePropagation
but they don’t seem to work.
I have also gone through several SO answers but none seem to fix my problem.
function handleFavClick(event) {
event.stopPropagation();
console.log(event);
}
<Link to={`/movies/${movie.id}`} key={movie.id}>
<div
className="card"
key={movie.id}
>
<img
src="/heart-icon.png"
alt="heart icon"
onClick={handleFavClick}
/>
<img
src="/card-image.png"
alt="original card image"
/>
</div>
</Link>
What could be the issue?
2
Answers
your code show follow this pattern. Event.preventDefault() works when submitting a form in order to prevent the page from reloading.
In other not to click on the link tag from react-router-dom, you should remove img tag from the Link tag.
import { Link } from "react-router-dom"
const onClickFunction = () =>{
}
export default onClickFunction;
To prevent the
Link
from being triggered when clicking on the heart icon while still allowing thehandleFavClick
function to execute, you can wrap theLink
with adiv
and place theonClick
event handler on thatdiv
. This way, clicking the heart icon won’t trigger theLink
. Here’s an updated version of your code: