All files / Rindu/components/PortalTarget PortalTarget.ts

92.3% Statements 12/13
50% Branches 2/4
100% Functions 2/2
92.3% Lines 12/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 3319x   19x   19x   13x           18x   18x   7x     7x     18x 7x     11x       11x    
import { PropsWithChildren, ReactPortal, useEffect, useState } from "react";
 
import { createPortal } from "react-dom";
 
import { TargetElementError } from "utils";
 
export default function PortalTarget({
  children,
  targetId,
}: PropsWithChildren<{
  targetId?: string | HTMLElement;
}>): ReactPortal | null {
  const [target, setTarget] = useState<Element | HTMLElement | null>();
 
  useEffect(() => {
    const targetElement =
      typeof targetId === "string"
        ? document.querySelector(`#${targetId}`)
        : targetId;
    setTarget(targetElement);
  }, [targetId]);
 
  if (target === undefined) {
    return null;
  }
 
  Iif (target === null) {
    throw new TargetElementError(targetId);
  }
 
  return createPortal(children, target);
}