Click Handling - Click out of a Modal in React


I’m working on the recipe box react project and I am building a modal to allow the user to add their new recipes. One of the features i wanted to implement is when a user clicks outside of the modal, the modal will close. I have this working now but it feels hacky.

Basically, what I’m doing is attaching a click handler to document. Whenever there is a click I check to see if the target of the click is outside of the modal div. If it is, i set the modalstate to false and no modal is rendered, otherwise, it stays open:

if ( === this.refs.outsideOfModal){
    modalMode: false

this works, but is there a better way? Originally, I tried to put a click listener on ONLY the html content outside of the modal div, but clicking in the modal would cause this event to fire too (which I do not understand as I thought events were supposed to bubble UP not bubble down) even though modal was a child of the container element.

If anyone could lend some guidance I’d really appreciate it. Thanks everyone

What you’re doing is more or less the best approach. See the following article for an explanation and some additional considerations:

I think it’s also important to address this comment.

document is at the very top of the DOM. So, your event is indeed bubbling UP. See the following diagram:

Events bubble up from the lower boxes to the higher boxes.

Hope that helps.


1 Like


Great read. Thanks for the consistent help Bill, I really appreciate it.

1 Like