13

Using React Hooks, I run into a TypeScript error when I initialize a ref as null, then try to access it later. This is a pared-down, illustrative example:

  const el = useRef(null);

  useEffect(() => {
    if (el.current !== null) {
      //@ts-ignore
      const { top, width } = el.current.getBoundingClientRect();
    }
  }, []);

  return <div ref={el}></div>

The @ts-ignore suppresses the error Object is possibly 'null'. Is it possible to write this without getting the error?

1 Answer 1

19

I found the answer here: https://fettblog.eu/typescript-react/hooks/#useref

The key is to assign a type to the ref: const el = useRef<HTMLDivElement>(null); then check carefully:

if (el && el.current){
  const { top, width } = el.current.getBoundingClientRect();
}
Sign up to request clarification or add additional context in comments.

1 Comment

The in-depth explanation here.

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.