WebViews in React Native

Webviews has many applications. It can be used to redirect or embed web application inside a React native app. The WebView component was first available in React Native version. It is a module maintained by the community. The only way to let the users visit an external link within an Android or React application is using WebViews. You can utilize the WebView component using react-native-webview. React-native-webview is the cross  platform module which can be used to attain the functionality.

Requirements

The requirements for using WebView are Node.js version 8 or above installed using npm or yarn, watchman, react-native-cli.

Installation

First initialize a new React Native project using the following command and then move to the created project directory.

# to generate a project directory

react-native-cli init RNWebviewsDemo

# navigate inside the project directory

cd RNWebViewsDemo

Then install react-native-webview package and lik the native bindings with the newly installed dependency.

# to install

yarn add react-native-webview

# to link

react-native link react-native-webview

For Android platforms version 6 and above  open android/gradle.properties and add the following.

android.useAndroidX=true

android.enableJetifier=true

To open the boilerplate application with react-native-cli run the below commands.

# for Mac users

react-native run-ios

# for Windows/Linux users

react-native run-android

A welcome screen will appear.

Implementation

                              We will create a simple WebView to see how it works. First we import the WebView component from react-native-webview to call web content to the native view.  Type below lines in the App.js file.

import React from 'react'

import { SafeAreaView, StyleSheet, StatusBar } from 'react-native'

import WebView from 'react-native-webview'

A source property loads the static HTML or URI. Inside the App function component render the WebView component.

const App = () => {

  return (

    <>

      <StatusBar barStyle='dark-content' />

      <SafeAreaView style={styles.flexContainer}>

       <WebView source={{ uri: 'https://heartbeat.fritz.ai/' }} />

      </SafeAreaView>

    </>

  )

}

 

const styles = StyleSheet.create({

  flexContainer: {

    flex: 1

  }

})

 

export default App

You will see the output on your device screen if you are using a device or an emulator etc. Using the methods like goBack and goForward you can handle navigation state and transitions. There are spinners which we can display on the screen while the page is loading. This can be done by adding ActivityIndicator component.