import { OneOf } from '@leafygreen-ui/lib' ; import React , { useLayoutEffect , useState } from 'react' ; import PropTypes from 'prop-types' ; import { createPortal } from 'react-dom' ; type PortalProps = { children ? : React . ReactNode ; } & OneOf < { container : HTMLElement ; className ? : never ; } , { className ? : string ; container ? : null ; } > ; function usePortalContainer ( customContainer ? ) { const [ container , setContainer ] = useState < HTMLElement | undefined > ( ) ; useLayoutEffect ( ( ) => { if ( customContainer ) { setContainer ( customContainer ) ; } else { const defaultContainer = document . createElement ( 'div' ) ; document . body . appendChild ( defaultContainer ) ; setContainer ( defaultContainer ) ; return ( ) => { defaultContainer . remove ( ) ; } ; } } , [ customContainer ] ) ; return container ; } function Portal ( props ) { const container = usePortalContainer ( props . container ?? undefined ) ; useLayoutEffect ( ( ) => { if ( container && ! props . container ) { container . className = props . className ?? '' ; } } , [ container , props . container , props . className ] ) ; if ( ! container ) { return null ; } return createPortal ( props . children , container ) ; } Portal . displayName = 'Portal' ; Portal . propTypes = { children : PropTypes . node , className : PropTypes . string , container : PropTypes . oneOfType ( [ PropTypes . node , PropTypes . object ] ) , } ; export default Portal ;