I'm trying to use useRef()
to get the size of a responsive image so that I can make other images that same size in other places. However, it's not getting the correct data for ref.current
.
I currently have
const [iconWidth, setIconWidth] = useState(0);
const ref = useRef();
useEffect(() => {
console.log("Ref: ", ref);
console.log("Client Width: ", ref.current.clientWidth);
setIconWidth(ref.current.clientWidth)
})
return (
<Fragment>
<div className="small-div">
<img src={imagePath} className='img-fluid' ref={ref}/>
</div>
<div className="large-div">
... other content that I want the same size images
</div>
</Fragment>
)
The weird thing is that from the console.log
, I get
// Logging `ref`
Ref : {current: img.img-fluid.border}
current: img.img-fluid.border
...
clientWidth: 56
// Logging `ref.current.clientWidth`
Client Width : 0
So it's apparently seeing the correct info in the main ref
object, but only when I try to access it with ref.current.clientWidth
that it's wrong and showing 0.
I've tried moving the ref to the div, as well as setting different triggers for useEffect
, but it's still not showing the correct data.
Is there something I need to be doing differently to make this work? Or is there a better way to go about getting the size of an element?