12

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?

Ilja
  • 44,142
  • 92
  • 275
  • 498

2 Answers2

10

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

Matei Radu
  • 2,038
  • 3
  • 28
  • 45
10

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

const textInputRef: React.RefObject<TextInput> = React.createRef();
jefelewis
  • 1,850
  • 1
  • 27
  • 63