Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(React Native) Load local HTML file into WebView

I try to load the local .html file into WebView in React Native:

// load local .html file
const PolicyHTML = require('./Policy.html');

// PolicyHTML is just a number of `1`
console.log('PolicyHTML:', PolicyHTML);

// will cause an error: JSON value '1' of type NSNumber cannot be converted to NSString
<WebView html={PolicyHTML} />

The .html file should be read as a string, not as a resource representative.

How can I load the .html file into WebView in React Native?


By the way, what is the type of those resource representatives from require()? Is it number?

like image 214
Xaree Lee Avatar asked Mar 17 '17 07:03

Xaree Lee


4 Answers

try it:

const PolicyHTML = require('./Policy.html');

<WebView
  source={PolicyHTML}
  style={{flex: 1}}
 />
like image 187
Fmussap Avatar answered Oct 03 '22 22:10

Fmussap


I come across this post searching for loading static html.
If your html code is retrieved using, for example, an API, you can render WebView in this way:

<WebView
    originWhitelist={['*']}
    source={{ html: html, baseUrl: '' }}
/>

Notice that originWhitelistis required as explained in the documentation:

Note that static html will require setting of originWhitelist for example to ["*"].

like image 32
Luca Davanzo Avatar answered Oct 03 '22 23:10

Luca Davanzo


<View style={{flex: 1}}>
    <WebView
      style={{flex: 1}}
      source={require("./resources/index.html")}
    />
</View>

To make WebView, the parent has to has a dimension or flex:1. We could set the WebView to flex: 1 too so that it fills up the parent.

like image 6
stevemu Avatar answered Oct 03 '22 21:10

stevemu


If you need to serve local assets as well, then:

  1. put all assets together with index.html into android/app/src/main/assets/www (You can copy them there with gradle task)

  2. Then:

  var uri = Platform.OS == "android" ?
    "file:///android_asset/www/index.html" :
    "./web/www/index.html"
  return <WebView source={{ uri }} />

** For iOS didn't tested, please add instruction, how assets should be stored

like image 2
Daniel Garmoshka Avatar answered Oct 03 '22 23:10

Daniel Garmoshka