`useDimensions` hook only responds on page resize.
Opened this issue · 0 comments
c4lliope commented
If something causes an SVG to resize in the page without a browser resize occurring -
say, as in my app, you're using Flexbox and waiting for your data to load and fill in the page -
then the useDimensions
hook you recommend becomes stuck using the original element dimensions.
Here is an upgraded copy I made which seems to run properly for any kind of element resizing.
I relied upon https://github.com/que-etc/resize-observer-polyfill for cross-browser resize detection.
import React from "react"
import ResizeObserver from 'resize-observer-polyfill';
export const useDimensions = (targetRef) => {
const getDimensions = () => {
const box = targetRef.current
? targetRef.current.getBoundingClientRect()
: {}
return {
width: box.width || 0,
height: box.height || 0
};
};
const [dimensions, setDimensions] = React.useState(getDimensions);
const handleResize = () => setDimensions(getDimensions());
const ro = new ResizeObserver((entries, observer) => handleResize());
React.useEffect(() => {
if(targetRef.current) return ro.observe(targetRef.current);
}, [targetRef])
return dimensions;
}
This hook is mainly copied from https://www.react-graph-gallery.com/histogram#responsiveness .
I'm releasing this upgraded sample as public domain.