Using createRef in react-native with typescript?
Asked Answered
O

2

13

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?

Octangle answered 12/10, 2018 at 8:54 Comment(0)
A
11

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

Aegir answered 12/10, 2018 at 9:6 Comment(1)
So, there is no way of using the type of a custom component in createRef? Like: const customCompRef = React.createRef<CustomComponentType>()Hairtail
S
10

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

const textInputRef: React.RefObject<TextInput> = React.createRef();
Slipper answered 6/2, 2020 at 21:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.