Created
April 4, 2020 17:37
-
-
Save SamSamskies/a5f9f8adfb248d4fe9c34ce2c7218397 to your computer and use it in GitHub Desktop.
Simple React Portal
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 React, { useRef, useEffect } from 'react'; | |
import { createPortal } from 'react-dom'; | |
const Portal: React.FC = ({ children }) => { | |
const el = useRef<HTMLDivElement | null>(null); | |
useEffect(() => { | |
el.current = document.createElement('div'); | |
document.body.appendChild(el.current); | |
return () => { | |
el.current!.remove(); | |
}; | |
}, []); | |
return el.current ? createPortal(children, el.current) : null; | |
}; | |
export default Portal; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment