mirror of
https://github.com/laurent22/joplin.git
synced 2024-12-06 08:36:52 +02:00
39 lines
782 B
TypeScript
39 lines
782 B
TypeScript
import shim from '../shim';
|
|
const { useCallback, useEffect, useState } = shim.react();
|
|
import useEventListener from './useEventListener';
|
|
|
|
interface Size {
|
|
width: number;
|
|
height: number;
|
|
}
|
|
|
|
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();
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, []);
|
|
|
|
useEventListener('resize', updateSize);
|
|
|
|
return size;
|
|
}
|
|
|
|
export default useElementSize;
|