1 | import {RefObject, useEffect} from 'react';
|
2 |
|
3 | function hasResizeObserver() {
|
4 | return typeof window.ResizeObserver !== 'undefined';
|
5 | }
|
6 |
|
7 | type useResizeObserverOptionsType<T> = {
|
8 | ref: RefObject<T | undefined> | undefined,
|
9 | onResize: () => void
|
10 | }
|
11 |
|
12 | export function useResizeObserver<T extends Element>(options: useResizeObserverOptionsType<T>) {
|
13 | const {ref, onResize} = options;
|
14 |
|
15 | useEffect(() => {
|
16 | let element = ref?.current;
|
17 | if (!element) {
|
18 | return;
|
19 | }
|
20 |
|
21 | if (!hasResizeObserver()) {
|
22 | window.addEventListener('resize', onResize, false);
|
23 | return () => {
|
24 | window.removeEventListener('resize', onResize, false);
|
25 | };
|
26 | } else {
|
27 |
|
28 | const resizeObserverInstance = new window.ResizeObserver((entries) => {
|
29 | if (!entries.length) {
|
30 | return;
|
31 | }
|
32 |
|
33 | onResize();
|
34 | });
|
35 | resizeObserverInstance.observe(element);
|
36 |
|
37 | return () => {
|
38 | if (element) {
|
39 | resizeObserverInstance.unobserve(element);
|
40 | }
|
41 | };
|
42 | }
|
43 |
|
44 | }, [onResize, ref]);
|
45 | }
|