I’m trying to create a custom hook that calculates the width and height of a given DOM element through useRef.
It calculates the dimensions however I’m not seeing any dynamic output. Meaning that as I resize the window, current width and height of the DOM element are not being updated. I need to toggle a css class based on the DOM element’s width.
This is my custom hook, which takes a ref as its sole parameter:
useDimensionObserver = refParam => {
if (refParam === null) return false;
const getDimensionsFromRef = refParam => ({ width: refParam.current?.getBoundingClientRect().width, height: refParam.current?.getBoundingClientRect().height }),
[dimensions, setDimensions] = React.useState(getDimensionsFromRef(refParam));
React.useEffect(() => {
const handleResize = () => setDimensions(getDimensionsFromRef(refParam));
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return refParam ? dimensions : null;
},
This is the component in which I make use of useDimensionObserver:
GeneralTotals = (props = IGeneralTotals) => {
const containerRef = React.useRef(null),
d = useDimensionObserver(containerRef);
console.log(d); // As I resize the window, the container is also being resized so d.width and d.height need to be made dynamic.
//I shall take action with 'd' potentially something like this...
//if(d !== null && d.width < 450) setToggleInvisibleClass(true)
return (<div className="card-title-tags" key="cal" ref={containerRef}>
.....
</div>);
};