3

I am in the process of creating my own custom ui component for react native in objective-c and so far everything works, except I can't seem to call any methods on my component. This is my objective-c

#import "RNTWebViewManager.h"
#import <WebKit/WebKit.h>

@interface RNTWebViewManager()

@property (strong, nonatomic) WKWebView *webView;

@end

@implementation RNTWebViewManager

@synthesize webView;

RCT_EXPORT_MODULE()

- (UIView *)view {
  webView = [[WKWebView alloc] init];
  return  webView;
}

RCT_EXPORT_METHOD(loadWebsite:(NSString *)url)
{
  RCTLogInfo(@"Opening url %@",url);
  [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
};

@end

And here is my corresponding javascript code:

import React, { Component } from 'react';
import {
  requireNativeComponent,
  AppRegistry,
  StyleSheet,
  Button,
  Text,
  View
} from 'react-native';

// Load Native iOS Components
var RNTWebView = requireNativeComponent('RNTWebView', null);

class WebView extends Component {
  render() {
    return (
      <RNTWebView style={styles.webView} />
    )
  }
}

export default class iOSComponents extends Component {
  componentDidMount() {
    RNTWebView.loadWebsite("http://www.google.com/");
  }
  render() {
    return (
      <View style={styles.webView}>
        <View style={styles.statusBar} />
        <WebView />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  statusBar: {
    height:22,
  },
  webView: {
    flex:1,
  }
});

AppRegistry.registerComponent('iOSComponents', () => iOSComponents);

When I try calling RNTWebView.loadWebsite("http://www.google.com") I get an error saying RNTWebView.loadWebsite is not a function.

Mμ.
  • 8,382
  • 3
  • 26
  • 36
Asleepace
  • 3,466
  • 2
  • 23
  • 36

1 Answers1

1

That's an incorrect way to call native component. You call it through the Native modules library.

import { NativeModules } from 'react-native';

// ..rest of your code

// The name of your native module is based on the objective c class name. I assume it to be 'RNTWebViewManager'
let RNTWebView = NativeModules.RNTWebViewManager

// call method
RNTWebView.loadWebsite('https://www.google.com');

For more info, the official documentation is here.

Mμ.
  • 8,382
  • 3
  • 26
  • 36
  • Awesome thanks! It doesn't throw an error now, but it also doesn't change the webview. I import the module like this: let RNTWebViewManager = NativeModules.RNTWebViewManager; and then call the function, but is it a different instance than the webview I am displaying? – Asleepace Jun 21 '17 at 22:07
  • 1
    Hi @Asleepace, you need to call the methods which you have exported through the native UI component by using UIManager's ```UIManager.dispatchViewManagerCommand``` – Rupesh Chaudhari Oct 23 '21 at 14:57