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);
},[]);
useRef(null)effectively returns a ref which has anullcurrent property, TypeScript warns you about it before you execute the code so you have to adapt it with a null check or an optional chaining operator just like you diduseRef()without the null makes no difference right since it's still undefined. I can accept your comment as the answer if you respond with that. ThanksuseLayoutEffectruns before render so that's why your ref is null. Is there any reason to useReact.useLayoutEffectinstead ofReact.useEffect