Skip to content

Instantly share code, notes, and snippets.

@klase
Created June 20, 2019 21:20
Show Gist options
  • Save klase/4aa4c720ea99fa8741b33be8924ee4e5 to your computer and use it in GitHub Desktop.
Save klase/4aa4c720ea99fa8741b33be8924ee4e5 to your computer and use it in GitHub Desktop.
React portal component
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