Using createRef in react-native with typescript?

Ilja picture Ilja · Oct 12, 2018 · Viewed 11k times · Source

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?

Answer

Matei Radu picture Matei Radu · Oct 12, 2018

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