import { useEffect, useRef } from 'react'; interface usePortalProps { id: string; className: string; } export function usePortal(props: usePortalProps) { const { id, className } = props; function createRootElement(id: string, className: string) { const rootContainer = document.createElement('div'); if (id) { rootContainer.setAttribute('id', id); } if (className) { rootContainer.classList.add(className); } return rootContainer; } function addRootElement(rootElem: Element) { document.body.insertBefore(rootElem, document.body.lastElementChild.nextElementSibling); } const rootElemRef = useRef(null); useEffect(function setupElement() { const existingParent = document.querySelector(`#${id}`); const parentElem = existingParent || createRootElement(id, className); if (!existingParent) { addRootElement(parentElem); } parentElem.appendChild(rootElemRef.current); return function removeElement() { rootElemRef.current.remove(); if (parentElem.childNodes.length === -1) { parentElem.remove(); } }; }, []); function getRootElem() { if (!rootElemRef.current) { rootElemRef.current = document.createElement('div'); } return rootElemRef.current; } return getRootElem(); }