Skip to content

Instantly share code, notes, and snippets.

@brandonpittman
Last active July 27, 2022 05:12
Show Gist options
  • Save brandonpittman/41c19d9cd900f8f8d4ebdc9bc6486a43 to your computer and use it in GitHub Desktop.
Save brandonpittman/41c19d9cd900f8f8d4ebdc9bc6486a43 to your computer and use it in GitHub Desktop.
usePortal
import {
createPortal as createReactPortal,
unmountComponentAtNode,
} from "react-dom";
import { useState, useCallback, useEffect } from "react";
export let usePortal = (el: Element = document.body) => {
let [portal, setPortal] = useState<{
render: Function;
remove: Function;
}>({
render: () => null,
remove: () => null,
});
const createPortal = useCallback((el) => {
let Portal = ({ children }: { children: Element }) =>
createReactPortal(children, el);
let remove = () => unmountComponentAtNode(el);
return { render: Portal, remove };
}, []);
useEffect(() => {
if (el) unmountComponentAtNode(el);
let newPortal = createPortal(el);
setPortal(createPortal(el));
return () => {
newPortal.remove();
};
}, [el, createPortal]);
return portal.render;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment