-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathuseResizeObserver.ts
More file actions
52 lines (42 loc) · 1.34 KB
/
useResizeObserver.ts
File metadata and controls
52 lines (42 loc) · 1.34 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
42
43
44
45
46
47
48
49
50
51
52
import {RefObject} from '@react-types/shared';
import {useEffect} from 'react';
import {useEffectEvent} from './useEffectEvent';
function hasResizeObserver() {
return typeof window.ResizeObserver !== 'undefined';
}
type useResizeObserverOptionsType<T> = {
ref: RefObject<T | undefined | null> | undefined,
box?: ResizeObserverBoxOptions,
onResize: () => void
}
export function useResizeObserver<T extends Element>(options: useResizeObserverOptionsType<T>): void {
// Only call onResize from inside the effect, otherwise we'll void our assumption that
// useEffectEvents are safe to pass in.
const {ref, box, onResize} = options;
let onResizeEvent = useEffectEvent(() => onResize());
useEffect(() => {
let element = ref?.current;
if (!element) {
return;
}
if (!hasResizeObserver()) {
window.addEventListener('resize', onResizeEvent, false);
return () => {
window.removeEventListener('resize', onResizeEvent, false);
};
} else {
const resizeObserverInstance = new window.ResizeObserver((entries) => {
if (!entries.length) {
return;
}
onResizeEvent();
});
resizeObserverInstance.observe(element, {box});
return () => {
if (element) {
resizeObserverInstance.unobserve(element);
}
};
}
}, [ref, box]);
}