useDimensions.tsx 666 B

123456789101112131415161718192021
  1. import {useCallback, useRef, useState} from 'react';
  2. import {useResizeObserver} from '@react-aria/utils';
  3. /**
  4. * Returns a ref to be added to an element and returns the dimensions of that element
  5. */
  6. export function useDimensions<Element extends HTMLElement>() {
  7. const elementRef = useRef<Element>(null);
  8. const [dimensions, setDimensions] = useState({height: 0, width: 0});
  9. const onResize = useCallback(() => {
  10. setDimensions({
  11. height: elementRef.current?.clientHeight || 0,
  12. width: elementRef.current?.clientWidth || 0,
  13. });
  14. }, [setDimensions]);
  15. useResizeObserver({ref: elementRef, onResize});
  16. return {elementRef, ...dimensions};
  17. }