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.
2 replies on “How to fix the ‘not assignable to type LegacyRef’ error when using React useRef with TypeScript?”
“unll”?
Fixed