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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

If we would like to use reference properties of useRef declared component then we should need to wait till component get mount. Before mount it mount if you would like to access it you will get an undefined error.

Error:

import React, { useRef } from "react";

export function App(props) {

  const ref = useRef()

  console.log(ref.current) // undefined

  return (
    <div className='App'>
      <h1 ref={ref}>Hello React.</h1>
    </div>
  );

}

Solution:
import React, { useRef } from "react";

export function App(props) {

  const ref = useRef()

  const seeRef = () => {
    console.log(ref.current) // <h1 ></h1>
  }

  return (
    <div className='App'>
      <h1 ref={ref}>Hello React.</h1>
      <button onClick={()=> seeRef()}>Click</button>
    </div>
  );

}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x