Skip to content

Instantly share code, notes, and snippets.

@tadeaspetak
Last active February 2, 2023 23:19
Show Gist options
  • Save tadeaspetak/aebcb1a56d6eaa8794157bda7833d3d9 to your computer and use it in GitHub Desktop.
Save tadeaspetak/aebcb1a56d6eaa8794157bda7833d3d9 to your computer and use it in GitHub Desktop.
export const usePortal = () => {
const portal = useRef(document.createElement("div"));
useEffect(() => {
const current = portal.current;
document.body.appendChild(portal.current);
return () => void document.body.removeChild(current); // let's avoid dangling `div`s
}, []);
return portal;
};
// then in our modal...
const portal = usePortal();
return ReactDOM.createPortal(
<div...</div>, {/* the entire thing from before */}
portal.current
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment