Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useRef "refers to a value, but is being used as a type here."

I'm trying to figure out how to tell react which element is being used as ref i.e. in my case

const circleRef = useRef<AnimatedCircle>(undefined);

AnimatedCircle is an SVG component from a third party library, and defining it this way causes error

enter image description here

Is there some universal way to define which element is ref?

like image 628
Ilja Avatar asked Apr 08 '19 15:04

Ilja


People also ask

What type does useRef return?

useRef returns a mutable ref object whose .current property is initialized to the passed argument ( initialValue ). The returned object will persist for the full lifetime of the component. Essentially, useRef is like a “box” that can hold a mutable value in its .current property.

How do I use useRef in react native TypeScript?

To use useRef with TypeScript, it is actually pretty easy, all you need to do is provide the type that you want to the function via open and closed chevrons like you would with other React hooks like so: const myRef = useRef<number>(0) .


3 Answers

In my case, I renamed the file as .ts instead of .tsx. Renaming it again fixed it.

like image 194
Ishmeet Singh Avatar answered Oct 19 '22 14:10

Ishmeet Singh


AnimatedCircle is a function, not a type. This means it cannot be used in TypeScript in place of a type, like in the generic constraint of useRef. Instead, you need to use the typeof operator to convert to a type:

const circleRef = useRef<typeof AnimatedCircle | null>(null);
like image 20
Dan Avatar answered Oct 19 '22 13:10

Dan


I was getting the same error in

ReactDOM.render(
<App store={store} persistor={persistor} basename={PUBLIC_URL} />,
document.getElementById("root");

And I renamed the file to .tsx and that fixed the problem. The reason is that, when you are using React or ReactDOM, you have to rename file to .tsx instead of ts. For JavaScript, .js works but for TypeScript, .ts don't work.

like image 12
DevLoverUmar Avatar answered Oct 19 '22 13:10

DevLoverUmar