Is it possible to detect when an element reference changes it's height? I tried using the following, but when the height of the element changes for whatever reason, the change is not detected. (Please consider that this must also work in IE11)
useEffect(() => {
// detect change in reference height
}, [elementRef])
I noticed another answer mentioning to use a ResizeObserver, but the answer is incomplete, so I'd like to add my own.
You can create a ResizeObserver inside a useEffect-hook, and then do what you want to do when the element changes its size. Remember to disconnect from the resizeObserver in the cleanup function.
useEffect(() => {
if (!elementRef.current) return;
const resizeObserver = new ResizeObserver(() => {
// Do what you want to do when the size of the element changes
});
resizeObserver.observe(elementRef.current);
return () => resizeObserver.disconnect(); // clean up
}, []);
As mentioned in the comments, it's also possible to use useCallback instead of useEffect.
You can create a ResizeObserver inside a useCallback-hook, and then do what you want to do when the element changes its size. React has an example on how to measure a DOM node.
const elementRef = useCallback(node => {
if (!node) return;
const resizeObserver = new ResizeObserver(() => {
// Do what you want to do when the size of the element changes
});
resizeObserver.observe(node);
}, []);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With