@slashid/react-primitives
Version:
Primitive components for the /id React SDK
26 lines (22 loc) • 640 B
text/typescript
/**
* Companion utility for <Teleport />
*
* Searches the DOM for a teleport target element
* with id [teleportId]. If none is found, creates
* one at the root of the DOM.
*
* @param teleportKey the key of teleport target
*
* @returns the portal element
*/
export const findOrCreateTeleportTarget = (
teleportKey: string
): HTMLElement => {
const element = globalThis.document.getElementById(teleportKey);
const targetExists = element !== null;
if (targetExists) return element;
const teleport = document.createElement("div");
teleport.id = teleportKey;
document.body.appendChild(teleport);
return teleport;
};