anbnyc
anbnyc

Reputation: 921

How can I avoid a TypeScript error with React useRef?

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?

Upvotes: 13

Views: 10014

Answers (1)

anbnyc
anbnyc

Reputation: 921

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

Upvotes: 19

Related Questions