Created
June 15, 2022 14:40
-
-
Save laszlo-horvath/eeaf94ea68881d1cd208d51437dbbcd8 to your computer and use it in GitHub Desktop.
React reusable Portal component
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 { useEffect, useRef, memo } from 'react'; | |
import { createPortal } from 'react-dom'; | |
const Portal = ({ children }) => { | |
// Keeps ref between renders | |
const el = useRef(null); | |
// Create element if empty (for the first render only) | |
if (!el.current) el.current = document.createElement('div'); | |
useEffect(() => { | |
const mount = document.body; | |
const { current } = el; | |
mount.appendChild(current); | |
// Clean up: remove DOM element when the component unmounts | |
return () => mount.removeChild(current); | |
}, []); // No dependencies to avoid rerenders | |
return createPortal(children, el.current); | |
}; | |
export default memo(Portal); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment