Introduction
In this blog, we will look into React Native WebView. React Native WebView is a native viewer for web content. It renders web content in native view. If you are new to React Native and are yet to set up your environment for the language, you can check out this React Native Development, Hooks in React JS
React Native WebView
React Native WebView is a component for loading web pages. The WebView component comes from the react-native library's core. The WebView has been moved from the react-native-core library to the react-native-webview library. For example,
import React, { Component } from 'react';
import { WebView } from 'react-native-webview';
export default class MyWeb extends Component {
render() {
return (
<WebView
source={{
uri: 'https://www.codingninjas.com'
}}
style={{ marginTop: 30 }}
/>
);
}
}
Output:
Note: To use the react-native-webview library, you first need to install it. The installation can be done using the command expo install react-native-webview if you are running the program using expo-cli. In the case of npm, the installation command is: npm i react-native-webview.
Props of WebView
- source: It contains the reference to the page that is to be displayed on the app. There are many ways to pass the source. The first method is to pass the HTML content as a text file, along with any authentication headers that may be required for image links or other purposes. The second option is to pass a URI, which can be either a local or a remote file.
- injectedJavascript: We can supply any js code to run at the start of the script using this prop. Instead of using the WebView, we could use the js code to open all of the links in the browser.
- onLoad: When the loading is complete, the method is invoked. The onLoadStart is invoked at the start of load, and the onLoadEnd method is called at the end of loading.
- onMessage: This can be used to communicate between the web view's window objects and the React Native side.
- injectJavascript: With a js code as an argument, this procedure can be invoked at any time. When called, this is immediately executed. This can be used to send information from the RN to the web view.