In this post, we cover how to use React refs with TypeScript in function and class components.

Creating strongly-typed refs in function components

The useRef hook can be used to access all the properties and methods of an element.

const element = React.useRef(null);
// can access all the properties and methods of `element` via `element.current` 
...
return (
  <SomeElement ref={element} />
);

It is commonly used when we need to invoke methods on an element imperatively. Below is an example:

function Search() {
  const input = React.useRef(null);
  React.useEffect(() => {
    if (input.current) {
      input.current.focus();
    }
  }, []);
  return (
    <form>
      <input ref={input} type="search" />
    </form>
  );
};

We are setting focus on an input when the component first renders.

The type of input.current is inferred as null if strict mode is on; otherwise, it is inferred as any. A type error also occurs when input.current is referenced if strict mode is on.

Not ideal. ๐Ÿ˜ž

We can explicitly define the type of the element returned from useRef by passing a generic type parameter:

const element = React.useRef<ElementType>(null);

So, we can explicitly type the ref in the Search component as follows:

const input = React.useRef<HTMLInputElement>(null);

The type error now disappears. ๐Ÿ˜ƒ

#react #typescript #javascript #web-development #developer

How to use React refs with TypeScript in Function and Class Components
34.45 GEEK