Created
May 4, 2022 23:48
-
-
Save bluepnume/fe2a578aa6b90e3e03fb39695455a994 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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