-
-
Save luooooob/cf5a7efa2824a9f729b899fb54901763 to your computer and use it in GitHub Desktop.
Revisions
-
amitnovick created this gist
Dec 28, 2019 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,43 @@ import React from "react"; import { createPortal } from "react-dom"; function usePortal() { const portalElRef = React.useRef(document.createElement("div")); React.useEffect(() => { document.body.appendChild(portalElRef.current); return () => { if (portalElRef.current) { document.body.removeChild(portalElRef.current); } }; }, [portalElRef]); const Portal = React.useCallback( ({ children }) => { if (portalElRef.current != null) return createPortal(children, portalElRef.current); return null; }, [portalElRef] ); return Portal; } export default usePortal; // Usage const ModalPortal = usePortal(); return ( <ModalPortal> <div className="overlay"> <div className="content"> <h2>This header is inside modal</h2> </div> </div> </ModalPortal> )