UNPKG

@mui/core

Version:

Unstyled React components with which to implement custom design systems.

90 lines (76 loc) 2.89 kB
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; import { exactProp, HTMLElementType, unstable_useEnhancedEffect as useEnhancedEffect, unstable_useForkRef as useForkRef, unstable_setRef as setRef } from '@mui/utils'; function getContainer(container) { return typeof container === 'function' ? container() : container; } /** * Portals provide a first-class way to render children into a DOM node * that exists outside the DOM hierarchy of the parent component. */ var Portal = /*#__PURE__*/React.forwardRef(function Portal(props, ref) { var children = props.children, container = props.container, _props$disablePortal = props.disablePortal, disablePortal = _props$disablePortal === void 0 ? false : _props$disablePortal; var _React$useState = React.useState(null), mountNode = _React$useState[0], setMountNode = _React$useState[1]; var handleRef = useForkRef( /*#__PURE__*/React.isValidElement(children) ? children.ref : null, ref); useEnhancedEffect(function () { if (!disablePortal) { setMountNode(getContainer(container) || document.body); } }, [container, disablePortal]); useEnhancedEffect(function () { if (mountNode && !disablePortal) { setRef(ref, mountNode); return function () { setRef(ref, null); }; } return undefined; }, [ref, mountNode, disablePortal]); if (disablePortal) { if ( /*#__PURE__*/React.isValidElement(children)) { return /*#__PURE__*/React.cloneElement(children, { ref: handleRef }); } return children; } return mountNode ? /*#__PURE__*/ReactDOM.createPortal(children, mountNode) : mountNode; }); process.env.NODE_ENV !== "production" ? Portal.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * The children to render into the `container`. */ children: PropTypes.node, /** * An HTML element or function that returns one. * The `container` will have the portal children appended to it. * * By default, it uses the body of the top-level document object, * so it's simply `document.body` most of the time. */ container: PropTypes /* @typescript-to-proptypes-ignore */ .oneOfType([HTMLElementType, PropTypes.func]), /** * The `children` will be under the DOM hierarchy of the parent component. * @default false */ disablePortal: PropTypes.bool } : void 0; if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line Portal['propTypes' + ''] = exactProp(Portal.propTypes); } export default Portal;