Skip to content

Instantly share code, notes, and snippets.

@brandoncc
Last active June 4, 2019 23:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brandoncc/96388e48106cfb6cc9f269b1968aaa30 to your computer and use it in GitHub Desktop.
Save brandoncc/96388e48106cfb6cc9f269b1968aaa30 to your computer and use it in GitHub Desktop.
import React, { useRef, useEffect } from "react";
import ReactDOM from "react-dom";
export default function Portal (props) {
const elRef = useRef(document.createElement("div"));
const rootRef = useRef();
useEffect(() => {
rootRef.current = document && document.getElementById("portal-root");
rootRef.current && rootRef.current.appendChild(elRef.current);
return () => {
rootRef.current && rootRef.current.removeChild(elRef.current);
};
}, []);
return ReactDOM.createPortal(props.children, elRef.current);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment