Home > Blockchain >  Can't access ref.current using React and Typescript
Can't access ref.current using React and Typescript

Time:05-08

Alright, I've read through every single thread and Github issue on this and couldn't find a real answer to why we can't console.log(ref.current) this on Typescript.

function App() {
  const ref = React.useRef<HTMLDivElement>(null);

  return (
    <div className="App">
      <Parent ref={ref} />
    </div>
  );
}

export default App;


const Parent = React.forwardRef<HTMLDivElement>(({}, ref) => {
  return (
    <div>
      <Child ref={ref}/>
    </div>
  );
});

export default Parent;




const Child = React.forwardRef<HTMLDivElement | null, IProps>(
  (props, ref) => {
    console.log(ref.current)
    return <div ref={ref}>Hello World</div>;
  }
);
export default Child;

I understand that ref can be null thats why it makes sense to console.log(ref?.current) but I dont understand why we can't access the current even with an if statement.enter image description here

CodePudding user response:

You need to assert the ref, use ref as MutableRefObject<HTMLDivElement> as it is not necessary for every ref to have the current property.

In your parent component, use (ref as MutableRefObject<HTMLDivElement>).current

CodePudding user response:

You can't access the the DOM node until it is mounted. Use useEffect hook to check after mount.

const Child = React.forwardRef<HTMLDivElement | null, IProps>(
    (props, ref) => {

        useEffect(()=>{
          console.log(ref.current)
      },[])
      
      return <div ref={ref}>Hello World</div>;
    }
  );
  • Related