From e45e44b717ea6072e46437b063b6cdd34744394f Mon Sep 17 00:00:00 2001 From: Cina Saffary Date: Wed, 21 Aug 2019 10:17:47 -0500 Subject: [PATCH] prevent modal from closing when modal is partial target of click. Fixes #29. --- src/Modal.js | 11 ++++++++--- test/index.js | 20 ++++++++++++++++++-- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/src/Modal.js b/src/Modal.js index 6536487..ae74e58 100644 --- a/src/Modal.js +++ b/src/Modal.js @@ -39,6 +39,8 @@ export default class ReactModal2 extends React.Component { closeOnBackdropClick: true }; + preventModalClose = false + componentDidMount() { if (ExecutionEnvironment.canUseDOM) { setFocusOn(ReactModal2.getApplicationElement(), this.modal); @@ -60,13 +62,15 @@ export default class ReactModal2 extends React.Component { } handleBackdropClick = () => { - if (this.props.closeOnBackdropClick) { + if (this.props.closeOnBackdropClick && !this.preventModalClose) { this.props.onClose(); } + + this.preventModalClose = false } handleModalClick = event => { - event.stopPropagation(); + this.preventModalClose = true } render() { @@ -78,7 +82,8 @@ export default class ReactModal2 extends React.Component {
this.modal = i} className={this.props.modalClassName} style={this.props.modalStyles} - onClick={this.handleModalClick} + onMouseDown={this.handleModalClick} + onMouseUp={this.handleModalClick} tabIndex="-1"> {this.props.children}
diff --git a/test/index.js b/test/index.js index e995f41..7ecdcbb 100644 --- a/test/index.js +++ b/test/index.js @@ -65,18 +65,34 @@ describe('ReactModal2', function() { expect(called).to.be.false; }); - it('should not call `onClose` when the modal is clicked', function() { + it('should not call `onClose` when the modal is the start target of a click', function() { var called = false; var onClose = function() { called = true; }; var dom = ; var instance = ReactDOM.render(dom, this.root); - TestUtils.Simulate.click(instance.modal); + TestUtils.Simulate.mouseDown(instance.modal); + TestUtils.Simulate.mouseUp(instance.backdrop); + TestUtils.Simulate.click(instance.backdrop); expect(called).to.be.false; }); + it('should not call `onClose` when the modal is the end target of a click', function() { + var called = false; + var onClose = function() { called = true; }; + + var dom = ; + var instance = ReactDOM.render(dom, this.root); + + TestUtils.Simulate.mouseDown(instance.backdrop); + TestUtils.Simulate.mouseUp(instance.modal); + TestUtils.Simulate.click(instance.backdrop); + + expect(called).to.be.false; + }); + it('should scope the focus on the modal when mounted', function() { var input = document.createElement('input'); document.body.appendChild(input);