I'm having an issue with event bubbling. I have a card that has onClick function. On the card, there is a heart icon that also has an onClick function. When I click the heart icon on the card to unlike a card, the onClick fn for the entire card is executing as well, which takes me to a different page that renders more details about the card, specifically, a food truck. How can I stop this from happening?
I tried this:
const removeFromFavorites = (e, truckId) => {
props.removeFromFavoriteTrucks(props.dinerId, truckId);
e.stopPropagation();
}
But with this code, I'm getting an error that says: "e.stopPropagation is not a function."
the card:
<Card className="truck-card" onClick={() => selectTruck(truck.id)}>
<CardActionArea>
<CardMedia
className="truck-img"
image={truck.image}
style={{ width: '100%' }}
/>
<i
className="like-icon"
class={filterThroughFavs(truck.id).length > 0 ? "fas fa-heart" : "far fa-heart"}
onClick={() => removeFromFavorites(truck.id)}
/>
<CardContent className="truck-contents">
<Typography className="truck-name" gutterBottom variant="h5" component="h2">
{truck.name}
</Typography>
<Typography className="cuisine-type" component="h3">
{truck.cuisine_type}
</Typography>
</CardContent>
</CardActionArea>
</Card>
the click handler functions:
const selectTruck = truckId => {
props.setSelectedTruck(truckId);
setInitialMode(false);
}
const removeFromFavorites = (truckId) => {
props.removeFromFavoriteTrucks(props.dinerId, truckId)
}
Update:
So what I needed to do was pass e into my inner div function, call e.stopPropagation inside of it and then put e inside of my onClick as well. *Sorry for the lack of eloquence in explaining this. Here is the code:
const removeFromFavorites = (e, truckId) => {
props.removeFromFavoriteTrucks(props.dinerId, truckId);
e.stopPropagation();
}
<i
className="like-icon"
class={ filterThroughFavs(truck.id).length > 0 ? "fas fa-heart" : "far fa-heart"}
onClick={(e) => removeFromFavorites(e, truck.id)}
/>
