Skip to content

Commit 22d5c3f

Browse files
markogresakeddywashere
authored andcommitted
fix(Modal): fix bug where closing modal removed wrong modal-open string in class (#410)
Example: initial body class: `no-modal-opened` open and close modal, body class: `no-ed modal-open`
1 parent 6ce004c commit 22d5c3f

2 files changed

Lines changed: 45 additions & 1 deletion

File tree

src/Modal.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,8 @@ class Modal extends React.Component {
151151
this._element = null;
152152
}
153153

154-
const classes = document.body.className.replace('modal-open', '');
154+
// Use regex to prevent matching `modal-open` as part of a different class, e.g. `my-modal-opened`
155+
const classes = document.body.className.replace(/(^| )modal-open( |$)/, ' ');
155156
document.body.className = mapToCssModules(classNames(classes).trim(), this.props.cssModule);
156157
setScrollbarWidth(this.originalBodyPadding);
157158
}

src/__tests__/Modal.spec.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -565,4 +565,47 @@ describe('Modal', () => {
565565
expect(document.getElementsByClassName('modal-dialog').length).toBe(0);
566566
expect(document.body.className).toBe('');
567567
});
568+
569+
it('should remove exactly modal-open class from body', () => {
570+
// set a body class which includes modal-open
571+
document.body.className = 'my-modal-opened';
572+
573+
const wrapper = mount(
574+
<Modal isOpen={isOpen} toggle={toggle}>
575+
Yo!
576+
</Modal>
577+
);
578+
579+
// assert that the modal is closed and the body class is what was set initially
580+
jasmine.clock().tick(300);
581+
expect(isOpen).toBe(false);
582+
expect(document.body.className).toBe('my-modal-opened');
583+
584+
toggle();
585+
wrapper.setProps({
586+
isOpen: isOpen
587+
});
588+
589+
// assert that the modal is open and the body class is what was set initially + modal-open
590+
jasmine.clock().tick(300);
591+
expect(isOpen).toBe(true);
592+
expect(document.body.className).toBe('my-modal-opened modal-open');
593+
594+
// append another body class which includes modal-open
595+
// using this to test if replace will leave a space when removing modal-open
596+
document.body.className += ' modal-opened';
597+
expect(document.body.className).toBe('my-modal-opened modal-open modal-opened');
598+
599+
toggle();
600+
wrapper.setProps({
601+
isOpen: isOpen
602+
});
603+
604+
// assert that the modal is closed and the body class is what was set initially
605+
jasmine.clock().tick(300);
606+
expect(isOpen).toBe(false);
607+
expect(document.body.className).toBe('my-modal-opened modal-opened');
608+
609+
wrapper.unmount();
610+
});
568611
});

0 commit comments

Comments
 (0)