-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathuseGridDimensions.ts
More file actions
41 lines (32 loc) · 1.13 KB
/
useGridDimensions.ts
File metadata and controls
41 lines (32 loc) · 1.13 KB
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
33
34
35
36
37
38
39
40
41
import { useLayoutEffect, useState } from 'react';
import { flushSync } from 'react-dom';
export function useGridDimensions({
gridRef
}: {
gridRef: React.RefObject<HTMLDivElement | null>;
}) {
const [inlineSize, setInlineSize] = useState(1);
const [blockSize, setBlockSize] = useState(1);
useLayoutEffect(() => {
const { ResizeObserver } = window;
// don't break in Node.js (SSR), jsdom, and browsers that don't support ResizeObserver
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (ResizeObserver == null) return;
const { clientWidth, clientHeight } = gridRef.current!;
setInlineSize(clientWidth);
setBlockSize(clientHeight);
const resizeObserver = new ResizeObserver((entries) => {
const size = entries[0].contentBoxSize[0];
// we use flushSync here to avoid flashing scrollbars
flushSync(() => {
setInlineSize(size.inlineSize);
setBlockSize(size.blockSize);
});
});
resizeObserver.observe(gridRef.current!);
return () => {
resizeObserver.disconnect();
};
}, [gridRef]);
return [inlineSize, blockSize] as const;
}