Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: ref.current is undefined (useRef())

I have an image and I want to store its dimensions, for placing icons depending of the dimensions. I do so with useRef() hook.

const componentRef=useRef()

Then I add this componentRef to the <img ref={componentRef}>. For rendering the icons, I call a function {setIcons}.

return(
  <div>
    <img ref={componentRef}/>
    {setIcons}
  </div>
)

This function again looks like this.

const setIcons=(
        props.positions_Reader.map((mac,i)=>(
            <Icon
                style={{
                  position:"absolute",
                  left:componentRef.current.getBoundingClientRect().x,
                  top:componentRef.current.getBoundingClientRect().y
                }}
            />
        ))
    )

The error occurs in this line left:componentRef.current.getBoundingClientRect().x

At the first render there is no error, but when I go back and open the component again, this error occurs. Are there any suggestions?

like image 736
OttherCreek Avatar asked Apr 28 '20 14:04

OttherCreek


1 Answers

The problem is that you are trying to use componentRef before it is actually being assigned. Make use of useEffect and store the styles in state, this will ensure the re-render when componentRef.current changes

function App() {
  const componentRef = React.useRef();
  const [style, setStyle] = React.useState({})

  useEffect(() => {
    setStyle({
      left: componentRef.current.getBoundingClientRect().x,
      top: componentRef.current.getBoundingClientRect().y
    })
  }, [componentRef.current])

  const setIcons = props.positions_Reader.map((mac, i) => (
    <Icon
      style={{
        position: "absolute",
        top: style.top + mac.x,
        left: style.left + mac.y
      }}
    />
  ));

  return (
    <div>
      <img ref={componentRef} />
      {setIcons}
    </div>
  );
}

Sample Demo

like image 190
Jagrati Avatar answered Oct 17 '22 07:10

Jagrati