Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: React Native useRef giving error "Object is possibly null"

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);
  },[]);
like image 505
wongz Avatar asked Sep 02 '25 06:09

wongz


1 Answers

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);
like image 56
Guerric P Avatar answered Sep 04 '25 21:09

Guerric P