@brizy/ui
Version:
React elements in Brizy style
40 lines (39 loc) • 1.38 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Portal = Portal;
const react_1 = require("react");
const react_dom_1 = require("react-dom");
function Portal({ className, node, children }) {
const elRef = (0, react_1.useRef)(null);
// this is deliberately done in render instead of useState + useEffect
// because useEffect is executed after render, which means that
// for the initial render, the state would have been null and this
// could break existent client code that doesn't expect it to be async
if (elRef.current === null || elRef.current.parentElement !== node) {
const el = node.ownerDocument.createElement("div");
if (className) {
el.className = className;
}
node.appendChild(el);
elRef.current = el;
}
(0, react_1.useEffect)(() => {
return () => {
if (elRef.current) {
node.removeChild(elRef.current);
}
};
}, [node]);
(0, react_1.useEffect)(() => {
if (!elRef.current) {
return;
}
if (className) {
elRef.current.className = className;
}
else {
elRef.current.removeAttribute("class");
}
}, [className]);
return elRef.current ? (0, react_dom_1.createPortal)(children, elRef.current) : null;
}