mirror of
https://github.com/scm-manager/scm-manager.git
synced 2025-11-09 23:15:43 +01:00
create portal root for toast on demand
This commit is contained in:
33
scm-ui/ui-components/src/usePortalRootElement.ts
Normal file
33
scm-ui/ui-components/src/usePortalRootElement.ts
Normal 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;
|
||||
Reference in New Issue
Block a user