import { FunctionComponent , useEffect , useState } from "react" ; import ReactDOM from "react-dom" ; import { useUIContext } from "../UIContext" ; function appendDivNode ( window ) { const div = window . document . createElement ( "div" ) ; window . document . body . append ( div ) ; div . setAttribute ( "data-portal" , "modal" ) ; return div ; } param open function useDOMNode ( open ) { const { renderWindow } = useUIContext ( ) ; const [ modalDOMNode , setModalDOMNode ] = useState < HTMLDivElement | null > ( null ) ; useEffect ( ( ) => { if ( open ) { const node = appendDivNode ( renderWindow ) ; setModalDOMNode ( node ) ; return ( ) => { node . parentElement ! . removeChild ( node ) ; setModalDOMNode ( null ) ; } ; } return ; } , [ open , renderWindow ] ) ; return modalDOMNode ; } const Portal = ( { children } ) => { const modalDOMNode = useDOMNode ( Boolean ( open ) ) ; if ( modalDOMNode ) { return ReactDOM . createPortal ( children , modalDOMNode ) ; } return null ; } ; export default Portal ;