Skip to content

Commit 2d8d870

Browse files
committed
fix(modals): group all modal portals into one parent node
1 parent 02e97bf commit 2d8d870

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

src/dialog/Dialog.jsx

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ export function Dialog({ children, ...props }) {
1212
<React.Fragment>
1313
<DialogTrigger open={open}>{children}</DialogTrigger>
1414

15-
<ModalPortal isOpen={isOpen()}>
15+
<ModalPortal isOpen={isOpen()} title={props.title}>
1616
<Modal {...props} onClose={close} isOpen={isOpen()} />
1717
</ModalPortal>
1818
</React.Fragment>

src/dialog/ModalPortal.jsx

+21-5
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,18 @@ import React, { useState, useEffect } from 'react';
22
import ReactDOM from 'react-dom';
33
import PropTypes from 'prop-types';
44

5-
export function ModalPortal({ children, isOpen }) {
5+
export function ModalPortal({ children, title, isOpen }) {
66
const [container, setContainer] = useState();
77

88
useEffect(() => {
9-
const body = document.getElementsByTagName('body')[0];
9+
const modalPortalsElem = getModalPortalsElem();
1010

1111
if (!container) {
1212
const containerElem = document.createElement('div');
1313

14-
body.appendChild(containerElem);
14+
containerElem.dataset.title = title;
15+
16+
modalPortalsElem.appendChild(containerElem);
1517
setContainer(containerElem);
1618
}
1719

@@ -20,9 +22,9 @@ export function ModalPortal({ children, isOpen }) {
2022
return;
2123
}
2224

23-
body.removeChild(container);
25+
modalPortalsElem.removeChild(container);
2426
};
25-
}, [container]);
27+
}, [container, title]);
2628

2729
//FIXME: prop to define if modal will be always included into DOM
2830
if (!container || !isOpen) {
@@ -41,3 +43,17 @@ export function ModalPortal({ children, isOpen }) {
4143
ModalPortal.propTypes = {
4244
children: PropTypes.oneOfType([PropTypes.node, PropTypes.arrayOf(PropTypes.node)]),
4345
};
46+
47+
function getModalPortalsElem() {
48+
let modalPortalsElem = document.querySelector('#modal-portals');
49+
50+
if (!modalPortalsElem) {
51+
const body = document.getElementsByTagName('body')[0];
52+
53+
modalPortalsElem = document.createElement('div');
54+
modalPortalsElem.id = 'modal-portals';
55+
body.appendChild(modalPortalsElem);
56+
}
57+
58+
return modalPortalsElem;
59+
}

0 commit comments

Comments
 (0)