Samira Arabgol
Samira Arabgol

Reputation: 389

observer div element size/dimensions using useRef and window resize event (React Hook)

I am trying to constantly observe/detect a div element size using React Hook JS. I have used different ways but every time I see a common issue where decreasing window size doesn't change the ref.current.offsetWidth but increasing it, will change ref.current.offsetWidth value.

Here is my code:

function Chart({}) {
    const targetRef = useRef(null);
    const [dimensions, setDimensions] = useState({width: 0, height: 0});

    const updateDimensions = debounce(() => {
        if(targetRef.current) {
            setDimensions({
                width: targetRef.current.offsetWidth,
                height: targetRef.current.offsetHeight
            });
        }
    }, 50);

    useEffect(() => {
        updateDimensions();
    }, []);

    useEffect(() => {
        window.addEventListener("resize", updateDimensions);
        updateDimensions();
        return () => {
            window.removeEventListener("resize", updateDimensions);
        };
    }, []);

    return (
        <div style={{minHeight: 250}} ref={targetRef}>
           <some svg component/>
        </div>

    );
}

Note: Re-rendering the entire app will update the dimensions, but I don't want to refresh the whole page to get the right size.

Upvotes: 3

Views: 5907

Answers (1)

ZeeCoder
ZeeCoder

Reputation: 991

If you want to measure the size of certain elements using refs (or using a raw element even), then I recommend this library: https://github.com/ZeeCoder/use-resize-observer

If you want to measure the size of the window specifically, then probably best to use something like this: https://github.com/jaredLunde/react-hook/tree/master/packages/window-size#readme

Upvotes: 1

Related Questions