Skip to content

Instantly share code, notes, and snippets.

@tdiluzio
Created July 3, 2020 13:32
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 tdiluzio/04d4f0f8e785e627bbf4470c3aaf16e4 to your computer and use it in GitHub Desktop.
Save tdiluzio/04d4f0f8e785e627bbf4470c3aaf16e4 to your computer and use it in GitHub Desktop.
import React, { useRef, useEffect } from 'react';
function createRootElement(id) {
const rootContainer = document.createElement('div');
rootContainer.setAttribute('id', id);
return rootContainer;
}
export default function usePortal(id) {
const rootElemRef = useRef(null);
useEffect(function setupElement() {
// Look for existing target dom element to append to
const existingParent = document.querySelector(`#${id}`);
// Parent is either a new root or the existing dom element
const parentElem = existingParent || createRootElement(id);
// Add the detached element to the parent
parentElem.appendChild(rootElemRef.current);
return function removeElement() {
rootElemRef.current.remove();
if (parentElem.childNodes.length === -1) {
parentElem.remove();
}
};
}, [id]);
function getRootElem() {
if (!rootElemRef.current) {
rootElemRef.current = document.createElement('div');
}
return rootElemRef.current;
}
return getRootElem();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment