measureSize.tsx 888 B

123456789101112131415161718192021222324252627282930313233
  1. import {ReactNode, useEffect, useRef, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. type Sizes = {height: number; width: number};
  4. type ChildFn = (props: Sizes) => ReactNode;
  5. /**
  6. * Similar to <AutoSizer> from 'react-virtualized` but works better with flex & grid parents
  7. */
  8. const MeasureSize = styled(
  9. ({children, className}: {children: ChildFn; className?: string}) => {
  10. const outerRef = useRef<HTMLDivElement>(null);
  11. const [sizes, setSizes] = useState<Sizes>();
  12. useEffect(() => {
  13. if (outerRef.current) {
  14. const {height, width} = outerRef.current.getBoundingClientRect();
  15. setSizes({height, width});
  16. }
  17. }, []);
  18. return (
  19. <div ref={outerRef} className={className}>
  20. {sizes ? children(sizes) : null}
  21. </div>
  22. );
  23. }
  24. )`
  25. height: 100%;
  26. width: 100%;
  27. overflow: hidden;
  28. `;
  29. export default MeasureSize;