create portal root for toast on demand

This commit is contained in:
Sebastian Sdorra
2019-12-12 10:20:50 +01:00
parent 3c615bc7ba
commit a973529328
4 changed files with 37 additions and 6 deletions

View File

@@ -0,0 +1,33 @@
import { useEffect, useState } from "react";
const createElement = (id: string) => {
const element = document.createElement("div");
element.setAttribute("id", id);
return element;
};
const appendRootElement = (rootElement: HTMLElement) => {
document.body.appendChild(rootElement);
};
const usePortalRootElement = (id: string) => {
const [rootElement, setRootElement] = useState<HTMLElement>();
useEffect(() => {
let element = document.getElementById(id);
if (!element) {
element = createElement(id);
appendRootElement(element);
}
setRootElement(element);
return () => {
if (element) {
element.remove();
}
setRootElement(undefined);
};
}, [id]);
return rootElement;
};
export default usePortalRootElement;