Skip to content

Instantly share code, notes, and snippets.

@mwmwmw
Last active December 8, 2022 13:59
Show Gist options
  • Save mwmwmw/b902eb0206f01500b82ca9938b2bbd90 to your computer and use it in GitHub Desktop.
Save mwmwmw/b902eb0206f01500b82ca9938b2bbd90 to your computer and use it in GitHub Desktop.
React Portal
import { useEffect, useMemo } from "react";
import { createPortal } from "react-dom";
export default function Portal({ children, root = 'overlay', pointerEvents = true }) {
const el = useMemo(() => document.createElement("div"), []);
const rootElement = useMemo(() => document.getElementById(root), [root]);
useEffect(() => {
rootElement.style = `pointer-events: ${pointerEvents ? 'all' : 'none'}`;
}, [rootElement, pointerEvents])
useEffect(() => {
rootElement.appendChild(el);
return () => {
rootElement.removeChild(el);
}
}, [rootElement, el])
return createPortal(children, el);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment