2021-08-16 16:20:14 +02:00
|
|
|
import shim from '../shim';
|
|
|
|
const { useCallback, useEffect, useState } = shim.react();
|
|
|
|
import useEventListener from './useEventListener';
|
|
|
|
|
|
|
|
interface Size {
|
2023-07-06 20:17:41 +02:00
|
|
|
width: number;
|
|
|
|
height: number;
|
2021-08-16 16:20:14 +02:00
|
|
|
}
|
|
|
|
|
2024-04-05 13:16:49 +02:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
|
2021-08-16 16:20:14 +02:00
|
|
|
function useElementSize(elementRef: any): Size {
|
|
|
|
const [size, setSize] = useState({
|
|
|
|
width: 0,
|
|
|
|
height: 0,
|
|
|
|
});
|
|
|
|
|
|
|
|
// Prevent too many rendering using useCallback
|
|
|
|
const updateSize = useCallback(() => {
|
|
|
|
const node = elementRef?.current;
|
|
|
|
if (node) {
|
|
|
|
setSize({
|
|
|
|
width: node.offsetWidth || 0,
|
|
|
|
height: node.offsetHeight || 0,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}, [elementRef]);
|
|
|
|
|
|
|
|
// Initial size on mount
|
|
|
|
useEffect(() => {
|
|
|
|
updateSize();
|
2022-08-19 13:10:04 +02:00
|
|
|
// eslint-disable-next-line @seiyab/react-hooks/exhaustive-deps -- Old code before rule was applied
|
2021-08-16 16:20:14 +02:00
|
|
|
}, []);
|
|
|
|
|
|
|
|
useEventListener('resize', updateSize);
|
|
|
|
|
|
|
|
return size;
|
|
|
|
}
|
|
|
|
|
|
|
|
export default useElementSize;
|