How to fix the ‘not assignable to type LegacyRef’ error when using React useRef with TypeScript?

To fix the ‘not assignable to type LegacyRef’ error when using React useRef with TypeScript, we pas in the type to the useRef hook.

For instance, we write

import React, { useRef } from "react";

const Test = () => {
  const node = useRef<HTMLDivElement>(unll);

  if (node?.current?.contains()) {
    console.log("current accessed");
  }

  return <div ref={node}></div>;
};

to call useRef to return the node ref.

Then we assign node as the value of the div’s ref prop.

And then we can access the div with node?.current.