Skip to content

Instantly share code, notes, and snippets.

@laszlo-horvath
Created June 15, 2022 14:40
Show Gist options
  • Save laszlo-horvath/eeaf94ea68881d1cd208d51437dbbcd8 to your computer and use it in GitHub Desktop.
Save laszlo-horvath/eeaf94ea68881d1cd208d51437dbbcd8 to your computer and use it in GitHub Desktop.
React reusable Portal component
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