UNPKG

@clayui/shared

Version:

ClayShared component

63 lines (61 loc) 2.23 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ClayPortal = void 0; var _provider = require("@clayui/provider"); var _classnames = _interopRequireDefault(require("classnames")); var _react = _interopRequireDefault(require("react")); var _reactDom = require("react-dom"); function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } /** * SPDX-FileCopyrightText: © 2019 Liferay, Inc. <https://liferay.com> * SPDX-License-Identifier: BSD-3-Clause */ const ClayPortalContext = /*#__PURE__*/_react.default.createContext(null); ClayPortalContext.displayName = 'ClayPortalContext'; const createDivElement = (className, id) => { const element = document.createElement('div'); if (className) { element.setAttribute('class', className); } if (id) { element.setAttribute('id', id); } return element; }; const ClayPortal = _ref => { let { children, className, containerRef, id, subPortalRef } = _ref; const { theme } = (0, _provider.useProvider)(); const parentPortalRef = _react.default.useContext(ClayPortalContext); const portalRef = _react.default.useRef(typeof document !== 'undefined' ? createDivElement((0, _classnames.default)(theme, className), id) : null); _react.default.useEffect(() => { const closestParent = parentPortalRef && parentPortalRef.current ? parentPortalRef.current : document.body; const elToMountTo = containerRef && containerRef.current ? containerRef.current : closestParent; if (elToMountTo && portalRef.current) { elToMountTo.appendChild(portalRef.current); } return () => { if (portalRef.current) { if (typeof portalRef.current.remove === 'function') { portalRef.current.remove(); } else if (elToMountTo) { elToMountTo.removeChild(portalRef.current); } } }; }, [containerRef, parentPortalRef]); const content = /*#__PURE__*/_react.default.createElement(ClayPortalContext.Provider, { value: subPortalRef ? subPortalRef : portalRef }, children); return portalRef.current ? /*#__PURE__*/(0, _reactDom.createPortal)(content, portalRef.current) : content; }; exports.ClayPortal = ClayPortal;