Skip to content

Instantly share code, notes, and snippets.

@bluepnume
Created May 4, 2022 23:48
Show Gist options
  • Save bluepnume/fe2a578aa6b90e3e03fb39695455a994 to your computer and use it in GitHub Desktop.
Save bluepnume/fe2a578aa6b90e3e03fb39695455a994 to your computer and use it in GitHub Desktop.
const useElementWithSize = () => {
const [ currentElement, setCurrentElement ] = useState(null);
const [ width, setWidth ] = useState(null);
const [ height, setHeight ] = useState(null);
const updateDimensions = (element) => {
setWidth(element?.offsetWidth);
setHeight(element?.offsetHeight);
};
useEffect(() => {
const onResize = () => {
if (currentElement) {
updateDimensions(currentElement);
}
};
window.addEventListener('resize', onResize);
return () => {
window.removeEventListener('resize', onResize);
};
}, [ currentElement ]);
const onElement = (element) => {
setCurrentElement(element);
updateDimensions(element);
};
return {
width,
height,
currentElement,
onElement
};
};
// Example:
const MyComponent = () => {
const helloWorldElement = useElementWithSize();
return (
<div ref={ helloWorldElement.onElement }>
Hello world! Current width: { helloWorldElement.width }
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment