Created
July 13, 2021 13:41
-
-
Save andyrichardson/2177e93ac6881e6eaa163d6671db0825 to your computer and use it in GitHub Desktop.
React portal example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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