2

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?

cchapman
  • 3,269
  • 10
  • 50
  • 68
  • 2
    See https://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays – the first log is the value of `ref` when you expand it in the console, the second is the value when the code logs it. You need to attach a listener to the image's onload event so that you get the width when the image has finished loading (it doesn't know what width it will have before it loads the image file.) – Guy Incognito Sep 15 '20 at 17:20
  • you can try with createRef() – SaimumIslam27 Sep 15 '20 at 17:58

0 Answers0