Skip to content

Instantly share code, notes, and snippets.

@andyrichardson
Created July 13, 2021 13:41
Show Gist options
  • Save andyrichardson/2177e93ac6881e6eaa163d6671db0825 to your computer and use it in GitHub Desktop.
Save andyrichardson/2177e93ac6881e6eaa163d6671db0825 to your computer and use it in GitHub Desktop.
React portal example
import { useLayoutEffect, useRef } from "react";
import { createPortal } from "react-dom";
const createPortalComponent = (el: HTMLElement) => ({ children }) => {
const ref = useRef<HTMLElement>(document.createElement("div"));
useLayoutEffect(() => {
el.appendChild(ref.current);
return () => el.removeChild(ref.current);
}, []);
return createPortal(children, ref.current);
};
export const ExamplePortal = createPortalComponent(
document.querySelector("#example-portal")
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment