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

Time:12-02

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

CodePudding user response:

I dont think its really a TypeScript issue, but more of an initialization problem. When you try to access your ref you do so in the way you would access an object and its null and not an object and thus throws the error you get. You could either verify the ref isnt null, or initialize it to some object so that you can properly query its properties:

// this
const ref = React.useRef({});



// or this
const ref = React.useRef(null);
React.useLayoutEffect(()=>{
    if(ref.current !== null){
       //do stuff
    }
  },[]);

CodePudding user response:

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);
  • Related