Skip to content

Commit

Permalink
Merge pull request #30 from 1000hz/fix-modal-close-behavior
Browse files Browse the repository at this point in the history
Prevent modal from closing when modal is partial target of click
  • Loading branch information
manatarms authored Aug 21, 2019
2 parents 0bee6ec + e45e44b commit 824469d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
11 changes: 8 additions & 3 deletions src/Modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ export default class ReactModal2 extends React.Component {
closeOnBackdropClick: true
};

preventModalClose = false

componentDidMount() {
if (ExecutionEnvironment.canUseDOM) {
setFocusOn(ReactModal2.getApplicationElement(), this.modal);
Expand All @@ -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() {
Expand All @@ -78,7 +82,8 @@ export default class ReactModal2 extends React.Component {
<div ref={i => 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}
</div>
Expand Down
20 changes: 18 additions & 2 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = <ReactModal2 onClose={onClose}/>;
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 = <ReactModal2 onClose={onClose}/>;
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);
Expand Down

0 comments on commit 824469d

Please sign in to comment.