Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

Component ref type in React Native with Typescript

$
0
0

I'm just starting to use Typescript in React Native and need help with refs and their types.

Please, see my code below:

type MyComponentProps = {  ref?: React.RefObject<typeof MyComponentViewNative>;  style?: ViewStyle;};type MyComponentState = {  permissionsGranted?: Boolean;};const ComponentName = 'MyComponentView';const MyComponentViewNative =  UIManager.getViewManagerConfig(ComponentName) != null    ? requireNativeComponent<MyComponentProps>(ComponentName)    : () => {        throw new Error(LINKING_ERROR);      };export class MyComponentView extends React.PureComponent<{}, {}> {  private viewRef: React.RefObject<typeof MyComponentViewNative> =    React.createRef<typeof MyComponentViewNative>();  public state: MyComponentState = {    permissionsGranted: false,  };  async componentDidMount() {    ...    this.setState({ permissionsGranted: true });  }  start(filePath: String) {    callViewMethod(this.viewRef, 'start', filePath);  }  render() {    const { permissionsGranted } = this.state;    return permissionsGranted ? (<MyComponentViewNative {...this.props} ref={this.viewRef} />    ) : (<View {...this.props} />    );  }}function callViewMethod(  viewRef: React.RefObject<typeof MyComponentViewNative>,  methodName: string,  ...params: any[]) {  if (viewRef.current == null) {    return;  }  if (Platform.OS === 'ios') {    NativeModules.MyComponentViewNative[methodName].apply(      NativeModules.MyComponentViewNative,      [findNodeHandle(viewRef.current), ...params]    );  } else if (Platform.OS === 'android') {    UIManager.dispatchViewManagerCommand(      findNodeHandle(viewRef.current),      methodName,      params    );  }}

My goal is to create a native component wrapper class MyComponentView, get a ref viewRef to an instance of the native component MyComponentViewNative in it and call it's method start. Seems I'm using ref the right way (at list it worked for me in plain JS many times), but setting its type is a thing I can't figure out.

So, tsc gives me a bunch of errors a-la the following one:

src/index.tsx:124:23 - error TS2345: Argument of type 'HostComponent<MyComponentProps> | (() => never)' is not assignable to parameter of type 'number | ComponentClass<any, any> | Component<any, any, any> | null'.  Type '() => never' is not assignable to type 'number | ComponentClass<any, any> | Component<any, any, any> | null'.124       [findNodeHandle(viewRef.current), ...params]

What am I doing wrong? What type should I use for the viewRef property? Or. maybe, I can somehow skip setting types explicitly?


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>