Last active
July 27, 2022 05:12
-
-
Save brandonpittman/41c19d9cd900f8f8d4ebdc9bc6486a43 to your computer and use it in GitHub Desktop.
usePortal
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 { | |
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