Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 696
anbnyc Avatar asked Aug 27 '19 21:08

anbnyc


People also ask

How do you focus with useRef in React?

Autofocusing using React useRef() and useEffect() Hooks We can also get the same functionality with the useRef() and useEffect() React Hooks. Here is the same form using these Hooks: import React, { useRef, useEffect } from "react"; const Form = () => { const emailInput = useRef(null); useEffect(() => { if (emailInput.

Why does useRef return null?

The "Object is possibly null" error is caused because the useRef() hook can be passed an initial value as an argument and we're passing it null as an initial value. The hook returns a mutable ref object whose . current property is initialized to the passed argument.

Which use cases should you use the useRef?

The useRef Hook allows you to persist values between renders. It can be used to store a mutable value that does not cause a re-render when updated. It can be used to access a DOM element directly.

Can I use useRef instead of useState?

If you want to update data and cause a UI update, useState is your Hook. If you need some kind of data container throughout the component's lifecycle without causing render cycles on mutating your variable, then useRef is your solution.


1 Answers

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();
}
like image 52
anbnyc Avatar answered Oct 26 '22 01:10

anbnyc