I'm using a ref on a View. Typescript is giving me an error "Object is possibly 'null'". What is the correct typing for a ref used on a View? Specifically I'm using an Animated.View
but I don't think that makes a difference.
Other answers on here are for ReactJS(web) and use const overlayEl = useRef<HTMLDivElement>(null);
but I'm looking for an answer for React Native.
const Component = () => {
const ref = React.useRef(null);
React.useLayoutEffect(()=>{
console.log(ref.current.clientHeight);
// ^ Error: "Object is possibly null" on the `ref.current` portion
},[]);
return (
<Animated.View ref={ref} style={{height: 100}}></Animated.View>
);
}
Things I tried:
const ref = React.useRef<React.FunctionComponent>(null);
const ref = React.useRef<React.ReactElement>(null);
const ref = React.useRef<React.MutableRefObject<null>>(null);
const ref = React.useRef(null) as React.MutableRefObject<null>;
console.log(ref?.current?.clientHeight);
// ^ Error: Property clientHeight does not exist on type 'never'
The only thing that works is this, but this isn't really a proper fix
React.useLayoutEffect(()=>{
const current = ref?.current || { clientHeight: 0 };
console.log(ref.current.clientHeight);
},[]);
Here is how useRef
is being typed in React:
function useRef<T>(initialValue: T): MutableRefObject<T>;
interface MutableRefObject<T> {
current: T;
}
That means once the MutableRefObject
is being typed, it always keeps its type so you have to type it properly with the angle brackets:
const ref = React.useRef<React.ElementRef<typeof View> | null>(null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With