I've been looking at a lot of modals made in React, and a lot of them seem to have this problem, so I have put together a simple example in jsFiddle to demonstrate the problem.
Code from the snippet:
handleOutsideClick = e => {
if (e.target.id === "modal-view-info") {
this.props.closeSelf();
}
}
Basically, it works (clicking outside the modal closes it). The problem is that I want to make it so that the modal only closes if the click event starts and finishes outside the modal. That is, if you start the mousedown outside the modal but drag it inside the modal for the corresponding mouseup, the modal should not close. Similarly, if you start the click inside the modal and end it outside the modal, it should not close.
I've been messing with it for a while, and I believe the problem is that browsers consider the e.Target
from a click event to be the parent element. That is, if you start clicking inside a child element, but then release the mouse button inside a parent element, the e.Target
will be the parent element. e.Target
will also be the parent element in the opposite case. This is making things tricky.
Is it possible to modify the snippet to incorporate this functionality? I'm already using this modal code all over my codebase so I'd prefer to just fix this, rather than go with a completely different design.
Don't listen for a click event on the entire modal. Instead, put a hidden div behind the modal that will capture clicks that are only outside the modal.
CSS
.modal-close {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
}
Component
class Modal extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<div id="modal-view-info" className="modal" >
<div className="modal-close" onClick={this.props.closeSelf} />
<div className="modal-content">
Hello how are you doing?
Well I hope!
</div>
</div>
</div>
)
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments