Skip to content

Instantly share code, notes, and snippets.

@sturmenta
Last active February 22, 2024 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sturmenta/75f09ebaabff158cca076c6e351a0189 to your computer and use it in GitHub Desktop.
Save sturmenta/75f09ebaabff158cca076c6e351a0189 to your computer and use it in GitHub Desktop.
react get div dimensions - using react hooks
import { useState, useEffect } from 'react';
const useContainerDimensions = containerRef => {
const getDimensions = () => ({
width: containerRef.offsetWidth,
height: containerRef.offsetHeight
});
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
useEffect(() => {
const handleResize = () => setDimensions(getDimensions());
if (containerRef) setDimensions(getDimensions());
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, [containerRef]);
return dimensions;
};
const GetContainerDimensions = ({ children, containerRef }) => children(useContainerDimensions(containerRef));
export default GetContainerDimensions;
// Example of use
// <div ref={ref => (this.customRef = ref)}></div>
//
// <GetContainerDimensions containerRef={this.customRef}>
// {({ width, height }) => <LoadingLayer isLoading={isLoading} width={width} height={height} />}
// </GetContainerDimensions>
@sturmenta
Copy link
Author

@sturmenta
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment