Created
July 3, 2020 13:32
-
-
Save tdiluzio/04d4f0f8e785e627bbf4470c3aaf16e4 to your computer and use it in GitHub Desktop.
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'; | |
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