Home > Enterprise >  React Native Functional Component - ref "No overload matches this call."
React Native Functional Component - ref "No overload matches this call."

Time:10-08

I'm new to JavaScript/TypeScript and React Native - especially the hooks. But I've got this functional component and I'm trying to figure out how to use refs with components. I'm not sure that I'm using the ref correctly here (I'm thinking I might need to put it in a different context, but that's not my main concern at the moment). What I'm trying to figure out is how to use refs/hooks in a React Native functional component.

Here's what I've got for now:

export default function BasicView(
  props: BasicViewProps
): JSX.Element {
  const basicRef = React.createRef();
  return (
    <View
      // Visual Studio Code error on ref: "No overload matches this call."
      // Note: I've also tried basicRef.current
      ref={basicRef}
      style={{
        maxHeight: 100,
        width: 100,
      }}
    >
      <Text>
        {props.txt}
      </Text>
    </View>
  );
}

As I played around with this, I noticed that this doesn't give me an error:

   ...
      // This works, though I'm not sure if it's useful at all if it's not a variable.
      ref={React.createRef()}
   ...

What's the appropriate way to use refs and createRef in React Native functional components? I've done a lot of searching around on the internet, and a lot of people seem to have success with refs but I haven't had any success with any of the methods I've seen. So what am I doing wrong here?

CodePudding user response:

In a function component, you will want to use the useRef() hook, not the createRef() function. This way, you'll get the same RefObject every time the component renders.

You can use it like so:

const BasicView: React.FC<BasicViewProps> = (props) => {
    // We need to tell TypeScript that this is a reference to a View,
    // as a RefObject can hold anything. The actual type of our
    // basicRef constant is RefObject<View | null>.
    const basicRef = React.useRef<View>(null);
    
    return (
        <View
            ref={basicRef}
            ...
        />
    );
};
  • Related