'Getting dynamic width of div after rendering
I want to get the width of a dynamic div after it's painted, but I can't tell how. This is what I am doing :
const ref=useRef();
useEffect(()=>{
console.log('REF',ref.current.offSetWidth)
},[])
return (
<div ref={ref}>
</div>
I tried window.resize eventListener, but it only gets triggered if the screen dimensions changed. My question is there anyway to get the width of a div after it renders on the screen ? I'm not setting the width beforehand, it's just taking 100% of parent element inside a flex box
Solution 1:[1]
You can use the ResizeObserver, a simple implementation with React could be something like this:
import {useRef, useEffect} from 'react'
export default function App() {
const divRef = useRef()
useEffect(() => {
new ResizeObserver(() => {
console.log('Width: ', divRef.current.clientWidth)
}).observe(divRef.current)
}, [])
return (
<div ref={divRef}>
</div>
);
}
Solution 2:[2]
Your code is working I think. Here is a short Typescript implementation to show my point:
...
const ref = useRef<HTMLDivElement>();
return (
<div ref={ref as MutableRefObject<HTMLDivElement>}>
<button onClick={() => console.log('REF', ref?.current?.clientWidth)}>TEST</button>
</div>
);
...
Console result on button click before resizing: [![enter image description here][1]][1]
Console result on button click after resizing: [![enter image description here][2]][2]
I guess the reason you never see the changes is that you have a use effect here that only runs once. Also note that changes in the ref object will not automatically trigger a re-render. [1]: https://i.stack.imgur.com/uCmz4.png [2]: https://i.stack.imgur.com/cWpVM.png
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | KOseare |
| Solution 2 | R0B1N |
