Skip to content

Commit ecf51b2

Browse files
hongricheddywashere
authored andcommitted
fix(Modal): unmounting nested modals (#321)
Unmounting nested modals should remove the matching number of `modal-open` classes from the body node. Previously, the updated class names were computed before its children are unmounted and only updated in the DOM afterwards. This can cause `modal-open` class name to be left on the body if any of its children is also a modal (which is also trying to remove those `modal-open` classes).
1 parent 5e98ea3 commit ecf51b2

2 files changed

Lines changed: 32 additions & 3 deletions

File tree

src/Modal.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,14 +115,13 @@ class Modal extends React.Component {
115115
}
116116

117117
destroy() {
118-
const classes = document.body.className.replace('modal-open', '');
119-
120118
if (this._element) {
121119
ReactDOM.unmountComponentAtNode(this._element);
122120
document.body.removeChild(this._element);
123121
this._element = null;
124122
}
125123

124+
const classes = document.body.className.replace('modal-open', '');
126125
document.body.className = mapToCssModules(classNames(classes).trim(), this.props.cssModule);
127126
setScrollbarWidth(this.originalBodyPadding);
128127
}

src/__tests__/Modal.spec.js

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,21 @@
11
import React from 'react';
22
import { mount } from 'enzyme';
3-
import { Modal } from '../';
3+
import { Modal, ModalBody } from '../';
44

55
describe('Modal', () => {
66
let isOpen;
77
let toggle;
88

9+
let isOpenNested;
10+
let toggleNested;
11+
912
beforeEach(() => {
1013
isOpen = false;
1114
toggle = () => { isOpen = !isOpen; };
15+
16+
isOpenNested = false;
17+
toggleNested = () => { isOpenNested = !isOpenNested; };
18+
1219
jasmine.clock().install();
1320
});
1421

@@ -452,4 +459,27 @@ describe('Modal', () => {
452459
instance.destroy();
453460
wrapper.unmount();
454461
});
462+
463+
it('should render nested modals', () => {
464+
isOpen = true;
465+
isOpenNested = true;
466+
const wrapper = mount(
467+
<Modal isOpen={isOpen} toggle={toggle}>
468+
<ModalBody>
469+
<Modal isOpen={isOpenNested} toggle={toggleNested}>
470+
Yo!
471+
</Modal>
472+
</ModalBody>
473+
</Modal>
474+
);
475+
476+
jasmine.clock().tick(300);
477+
expect(wrapper.children().length).toBe(0);
478+
expect(document.getElementsByClassName('modal-dialog').length).toBe(2);
479+
expect(document.body.className).toBe('modal-open modal-open');
480+
481+
wrapper.unmount();
482+
expect(document.getElementsByClassName('modal-dialog').length).toBe(0);
483+
expect(document.body.className).toBe('');
484+
});
455485
});

0 commit comments

Comments
 (0)