Last active
February 22, 2024 19:49
-
-
Save sturmenta/75f09ebaabff158cca076c6e351a0189 to your computer and use it in GitHub Desktop.
react get div dimensions - using react hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
better way of doing this: https://gist.github.com/sturmenta/dfa8c93d4b54d03ac2d592b23c228cd6