-
-
Save luooooob/cf5a7efa2824a9f729b899fb54901763 to your computer and use it in GitHub Desktop.
This file contains 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 characters
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> | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment