Skip to content

Instantly share code, notes, and snippets.

@mrwest808
Created March 12, 2020 11:35
Show Gist options
  • Save mrwest808/853e0435ba34f4ce4a4687282e39e7f5 to your computer and use it in GitHub Desktop.
Save mrwest808/853e0435ba34f4ce4a4687282e39e7f5 to your computer and use it in GitHub Desktop.
import { ReactNode, useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';
interface PortalProps {
children: ReactNode;
id: string;
}
export default function Portal({ children, id }: PortalProps) {
const elRef = useRef<HTMLElement>(null);
function getElement() {
if (!elRef.current) {
// @ts-ignore
elRef.current = document.createElement('div');
}
return elRef.current!;
}
useEffect(() => {
const mountElement = document.getElementById(id);
mountElement?.appendChild(getElement());
return () => {
mountElement?.removeChild(getElement());
elRef.current?.remove();
};
}, [id]);
return createPortal(children, getElement());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment