Using createRef in react-native with typescript? Using createRef in react-native with typescript? reactjs reactjs

Using createRef in react-native with typescript?


The first issue can be solved with a null check before proceeding with your logic since React.createRef() can also return null:

componentDidMount() {  if(this.circleRef !== null && this.circleRef.current !== null) {    this.circleRef.current.setNativeProps({      someProperty: someValue    });  }}

The second is solved by passing the class name of the Node element for which you want to create a reference. For example, if your referenced element is a <Text>, then do:

circleRef = React.createRef<Text>();

This way, circleRef will be correctly typed and setNativeProps will exist if and only if the referenced component is directly backed by a native view:

The methods [of current] are available on most of the default components provided by React Native. Note, however, that they are not available on composite components that aren't directly backed by a native view. This will generally include most components that you define in your own app. - Direct Manipulation - React Native documentation


You can add Typescript typings to a React Native Ref like this:

const textInputRef: React.RefObject<TextInput> = React.createRef();