简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM