JavaScript: Preventing Parent Event When Child Event Is Triggered
I created a React JS web application called Vacay Away that helps organize your vacation schedule. Read more about it here!
An issue I came across while setting up my Vacation component’s event handlers was that when I clicked on a child event trigger, the event on the parent component was also triggered simultaneously. More specifically, when I clicked the delete icon on a vacation component, it would not only delete the vacation, but also trigger the event on the card and route to the vacations show page (which didn’t exist anymore because I deleted the vacation).
Then I learned about using the stopPropagation()
method of the Event interface to prevent further propagation, or bubbling up to the parent elements.
In my code, my parent element is the <CardActionArea>
while my child element is the <IconButton>
. When the onClick is triggered in my child element, I want to stop the propagation to my parent element’s onClick event.
<CardActionArea onClick={showPageRoute} >
<Card container className={classes.card} elevation={5}>
<CardHeader
action={
<IconButton onClick={(e) => handleDelete(vacation.id, e)}>
<DeleteOutlined color="primary" />
</IconButton>
}
/> /** Code for Card Content **/
</Card>
</CardActionArea>
My handleDelete
is a function passed down as props from my parent component, Vacation List. Therefore, I made sure to stop any propagations when I trigger the event, like so:
handleDelete = (vacationId, e) => {
if(e && e.stopPropagation) e.stopPropagation(); /** code to delete the vacation **/}
If the event exists and stopPropagation
is supported in the browser, any bubbling of events will be cancelled. No redirecting to a non-existent page!
Closing Remarks
I thought this native Javascript method was pretty handy and thought I would share.
I also learned that there is an equivalent called cancelBubble
, the Microsoft method, versus stopPropagation
being a W3C method. Instead of calling e.stopPropagation()
in the above example, you can set e.cancelBubble = true
as a boolean value.