Created
April 23, 2019 13:36
-
-
Save zgabievi/0aab54bb44015275cdb27a5ed573018c to your computer and use it in GitHub Desktop.
React Portals with Hooks
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'; | |
// | |
const createRootElement = (id: string): Element => { | |
const rootContainer = document.createElement('div'); | |
rootContainer.setAttribute('id', id); | |
return rootContainer; | |
}; | |
// | |
const addRootElement = (rootElem: Element): void => { | |
document.body.insertBefore( | |
rootElem, | |
document.body.lastElementChild.nextElementSibling | |
); | |
}; | |
// | |
const usePortal = (id: string): Function => { | |
const rootElemRef = useRef(null); | |
useEffect(() => { | |
const existingParent = document.querySelector(`#${id}`); | |
const parentElem = existingParent || createRootElement(id); | |
if (!existingParent) { | |
addRootElement(parentElem); | |
} | |
parentElem.appendChild(rootElemRef.current); | |
return function removeElement() { | |
rootElemRef.current.remove(); | |
if (parentElem.childNodes.length === -1) { | |
parentElem.remove(); | |
} | |
}; | |
}, []); | |
return () => { | |
if (!rootElemRef.current) { | |
rootElemRef.current = document.createElement('div'); | |
} | |
return rootElemRef.current; | |
}; | |
}; | |
export default usePortal; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment