Search code examples
typescriptreact-nativeref

Problem associating a reference to a view in a react native project with typescript


I have created a react-native project with the typescript template

npx react-native init myApp --template react-native-template-typescript

When I associate a ref to a View in a tsx file I have this error.

No overload matches this call. Overload 1 of 2, '(props: ViewProps | Readonly): View', gave the following error. Type 'MutableRefObject' is not assignable to type 'LegacyRef | undefined'. Overload 2 of 2, '(props: ViewProps, context: any): View', gave the following error. Type 'MutableRefObject' is not assignable to type 'LegacyRef | undefined'

If I change the file extension from .tsx to .js the error dissapears so I suppose this is a typescript problem. Please, anybody knows how to handle this?

These are the versions I'm using and a code example

import {View, Text} from 'react-native';

const Test = () => {
  const containerRef = useRef();

  return (
    <View ref={containerRef}>
      <Text>Hi</Text>
    </View>
  );
};

export default Test;
"react": "17.0.1",
"react-native": "0.64.0",
"typescript": "^3.8.3"

Solution

  • For me this solution is working, maybe is useful for anybody. I have associated a generic with the element type of the reference

    ```const containerRef = useRef<View>(null); ```