Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-native-webview load a local HTML file but got plain text

I try to load a HTML file depends on someother .js file.

So I write code like this, but got plain text in webview.

render = () => {
    let source;
    if (__DEV__) {
      source = require('./vendor/Editor/index.html');
    } else {
      source =
        Platform.OS === 'ios'
          ? require('./vendor/Editor/index.html')
          : {uri: 'file:///android_asset/vendor/Editor/index.html'};
    }

    return (
      <WebView
        startInLoadingState
        source={source}
        onMessage={this.handleMessage}
        automaticallyAdjustContentInsets={false}
        style={[
          AppStyles.container,
          styles.container,
          {height: this.state.visibleHeight},
        ]}
      />
    );
  };

enter image description here

And I simplify the code like this, but it doesn't work too.

  render = () => {
    setTimeout(() => {
      this.webview.injectJavaScript(
        'window.ReactNativeWebView.postMessage(document.body.innerHTML)',
      );
    }, 3000);

    return (
      <WebView
        source={require('./vendor/GrEditor/index.html')}
        onMessage={e => console.log('e: ', e)}
      />
    );
  };

Sorry for poor grammar.

like image 292
Desmond Chen Avatar asked Apr 07 '20 02:04

Desmond Chen


People also ask

How do I open an HTML file in react native?

For Android put the file inside React_Native_Project -> android -> app -> src -> main -> assets -> index. html . You have to manually make the assets folder.

How do you call a HTML file in react?

If you want to include static html in ReactJS. You need to use html-loader plugin if you are using webpack to serve your react code. That is it. Now you can use static html files to load your html files in react.


1 Answers

To load local html file in android you need to use android asset path even in dev mode. So it will be like this:

let source = Platform.OS === 'ios'
          ? require('./vendor/Editor/index.html')
          : {uri: 'file:///android_asset/vendor/Editor/index.html'};

Copy your vendor folder in assets folder(project_folder\android\app\src\main\assets) of android.
Here is the link for your reference: https://github.com/react-native-community/react-native-webview/blob/master/docs/Guide.md#loading-local-html-files

like image 84
Ankit Makwana Avatar answered Sep 23 '22 18:09

Ankit Makwana