Hi FCC,
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 (e.target === this.refs.outsideOfModal){
this.setState({
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