Skip to content

Instantly share code, notes, and snippets.

@sagar-gavhane
Created November 7, 2018 06:00
Show Gist options
  • Save sagar-gavhane/6b8b52978206242b4b7b7e16aeee4a8d to your computer and use it in GitHub Desktop.
Save sagar-gavhane/6b8b52978206242b4b7b7e16aeee4a8d to your computer and use it in GitHub Desktop.
Observe for element resize.
import React, { useState, useEffect, useRef, } from "react";
const useElementResizer = (ref) => {
const [contentRect, setContentRect] = useState(ref.current ? ref.current.getBoundingClientRect() : {});
useEffect(() => {
if (!ref.current) return;
const observer = new window.ResizeObserver(entries => setContentRect(entries[0].contentRect));
observer.observe(ref.current);
return () => observer.disconnect(ref.current);
}, [ref]);
return contentRect;
}
const Component = () => {
const ref = useRef(null);
const styles = {
width: '50%',
height: '200px',
backgroundColor: '#2196f3',
margin: '0px auto',
padding: '25px',
};
const { width, height, } = useElementResizer(ref);
return (
<div>
<div className="box" style={styles} ref={ref}>
{width} x { height}
</div>
</div>
);
}
export default Component;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment