Using createRef in react-native with typescript?

14,009

Solution 1

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

Solution 2

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

const textInputRef: React.RefObject<TextInput> = React.createRef();
Share:
14,009

Related videos on Youtube

Ilja
Author by

Ilja

That dev at the local ☕️ shop sipping on late.

Updated on July 03, 2022

Comments

  • Ilja
    Ilja almost 2 years

    I am trying to figure out how I need to use React.createRef() in react native with typescript as following code throws errors

     // ...
    
      circleRef = React.createRef();
    
      componentDidMount() {
        this.circleRef.current.setNativeProps({
          someProperty: someValue
        });
      }
    
      // ...
    

    Currently following errors are thrown for this.circleRef.current.setNativeprops

    [ts] Object is possibly 'null'. (property) React.RefObject<{}>.current: {} | null

    and

    [ts] Property 'setNativeProps' does not exist on type '{}'. any

    any ideas?

  • Pedro Romano Barbosa
    Pedro Romano Barbosa about 4 years
    So, there is no way of using the type of a custom component in createRef? Like: const customCompRef = React.createRef<CustomComponentType>()