Categories
React Answers

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

Spread the love

Sometimes, we want to fix the ‘not assignable to type LegacyRef’ error when using React useRef with TypeScript.

In this article, we’ll look at how to fix the ‘not assignable to type LegacyRef’ error when using React useRef with TypeScript.

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 pass in the type to the useRef hook.

For instance, we write

import React, { useRef } from "react";

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

  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.

Conclusion

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

2 replies on “How to fix the ‘not assignable to type LegacyRef’ error when using React useRef with TypeScript?”

Leave a Reply

Your email address will not be published. Required fields are marked *