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); },[]);