I am encountering an issue with using a ref on a View in React Native. TypeScript is throwing the error "Object is possibly 'null'". What is the correct way to type a ref used on a View? I am specifically working with an Animated.View
, although it may not be relevant.
Previous solutions provided are for ReactJS(web) and utilize
const overlayEl = useRef<HTMLDivElement>(null);
. I am seeking a solution tailored 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>
);
}
The approaches I have attempted include:
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 workaround that functions is the following, but it is not a proper solution:
React.useLayoutEffect(()=>{
const current = ref?.current || { clientHeight: 0 };
console.log(ref.current.clientHeight);
},[]);