Created
June 20, 2019 21:20
-
-
Save klase/4aa4c720ea99fa8741b33be8924ee4e5 to your computer and use it in GitHub Desktop.
React portal component
This file contains hidden or 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, { useState, useEffect, useRef } from "react"; | |
import ReactDOM from "react-dom"; | |
const Portal = ({ children }) => { | |
const [attachedToDom, setAttachedToDom] = useState(false); | |
const el = useRef(null); | |
useEffect(() => { | |
el.current = document.createElement("div"); | |
document.body.appendChild(el.current); | |
setAttachedToDom(true); | |
return () => { | |
document.body.removeChild(el.current); | |
}; | |
}, []); | |
return attachedToDom ? ReactDOM.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