Why is the my reference, which I created using `useRef`, producing this error message?

1k views Asked by At

I created a reference like so for the animation on a circle svg:

const circleRef = useRef(null);

And in a useEffect, I have this line of code which is producing the error:

circleRef.current!.setNativeProps({
  strokeDashoffset,
});

This is the produced error message:

Property 'setNativeProps' does not exist on type 'never'.

Any ideas as to why this is happening? Seems like a typing error to me, but I could be wrong

1

There are 1 answers

2
emeraldsanto On

TypeScript doesn't know the type of the ref that will be held by circleRef since no type argument is given and the initial value is null. The inferred type is then never.

You can simply do:

// Change `View` to whatever the type of component is.
const circleRef = useRef<View>(null);

I would also recommend to use the ? operator instead of the ! operator to prevent a crash if the ref ever happens to not be defined when this code runs:

circleRef.current?.setNativeProps({ strokeDashoffset });