ReactNative: WebView with local content

Sneha Bagri
2 min readFeb 7, 2018

--

WebView in ReactNative can be used to load web content in native view. Recently, I had to integrate an external web widget inside my app with the structure as below:

The index.html has references to javascript inside ‘js’ folder and styles inside ‘css’ folder.

TLDR

  1. Copy static html (ex:- index.html) and its resources to be loaded in web view to the following paths:
  • Android: <react-native-project>/android/app/src/main/assets/
  • iOS: <react-native-project>/ios/<new group as folder>/ (Note: “New group as folder” will ensure all its contents are bundled into the IPA file.)

2. WebView should have the uri prop for iOS and android as shown below:

const isAndroid=  Platform.OS==='android'..... ..... .....<WebView source:{{uri: isAndroid?'file:///android_asset/widget/index.html'
:'./external/widget/index.html'}}/>

4. You can find the sample code here.

First Approach

import React, { Component } from 'react'
import {WebView} from 'react-native'
import Widget from './external/widget/index.html'
class ExternalWidget extends Component {
render()
{
<WebView source={Widget} scalesPageToFit/>
}
}
export default ExternalWidget

This worked perfectly fine when running in debug mode on simulator/emulator/real device.

Issue with release mode :- Only html gets bundled in the apk/app/ipa package. The dependencies are ignored and thus the HTML does not work as expected.

Final Approach

We need to add the dependencies of widget along with the html in the native resource directory for both android and ios as explained below:-

Android

  1. Create assets folder by clicking on File->New->Folder-> Assets folder on android studio.
  2. Add the widget to the assets folder as seen below:

3. The code for the External Widget will be as below:

import React, { Component } from 'react'
import {WebView} from 'react-native'
class ExternalWidget extends Component {
render()
{
<WebView
source={{uri:'file:///android_asset/widget/index.html'}}
scalesPageToFit/>
}
}
export default ExternalWidget

IOS

  1. Go to xcode-> main app folder -> add new group with folder callled ‘external’ -> add the widget files as shown below:

2. The code for external widget will be as below:

import React, { Component } from 'react'
import {WebView} from 'react-native'
class ExternalWidget extends Component {
render()
{
<WebView source={{uri:'./external/widget/index.html'}}
scalesPageToFit/>
}
}
export default ExternalWidget

The final sample code can be found here.

--

--