MCPcopy Create free account
hub / github.com/NativeScript/SimDeck / useElementSize

Function useElementSize

packages/client/src/shared/hooks/useElementSize.ts:5–34  ·  view source on GitHub ↗
(
  element: T | null,
)

Source from the content-addressed store, hash-verified

3import type { Size } from "../../features/viewport/types";
4
5export function useElementSize<T extends Element>(
6 element: T | null,
7): Size | null {
8 const [size, setSize] = useState<Size | null>(null);
9
10 useEffect(() => {
11 if (!element) {
12 setSize(null);
13 return;
14 }
15
16 const rect = element.getBoundingClientRect();
17 if (rect.width > 0 && rect.height > 0) {
18 setSize({ width: rect.width, height: rect.height });
19 }
20
21 const observer = new ResizeObserver((entries) => {
22 const nextRect = entries[0]?.contentRect;
23 if (!nextRect) {
24 return;
25 }
26 setSize({ width: nextRect.width, height: nextRect.height });
27 });
28
29 observer.observe(element);
30 return () => observer.disconnect();
31 }, [element]);
32
33 return size;
34}

Callers 1

AppShellFunction · 0.90

Calls 1

disconnectMethod · 0.65

Tested by

no test coverage detected