1

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

7
  • where are you using the Child component? Commented May 7, 2022 at 14:22
  • @Shan sorry, just fixed it up. check Parent component Commented May 7, 2022 at 14:23
  • Is this answer solve your problem, stackoverflow.com/questions/62238716/… Commented May 7, 2022 at 14:23
  • @RitikBanger I dont know if that answer is outdated, but its not working anymore Commented May 7, 2022 at 14:25
  • In your parent component, use (ref as MutableRefObject<HTMLDivElement>).current Commented May 7, 2022 at 14:26

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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>;
    }
  );

1 Comment

still getting the same error!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.