Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 commented May 4, 2022

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