Today we are going to learn how we can communicate a web app created with React with a WebView in React Native, and also use the postMessage() function of JavaScript. This is very useful for creating interfaces with web content and implementing them within a mobile app.
React Native
We will use the library react-native-webview
npm i react-native-webview --save
Import it:
import { WebView } from 'react-native-webview';
The first thing we need to do is create a WebView where we will load the URL we want to handle.
<WebView onMessage={onMessage} mixedContentMode="compatibility" source={{ uri: urlCargar }} />
We put our web address to load in urlCargar.
And to get the onMessage, we will create this function:
function onMessage(data) { if (data != null && data.nativeEvent != null && data.nativeEvent.data != null) { //If it is not JSON (we receive plain text): //alert(dataReturned); //If a JSON object is received: var dataReturned = JSON.parse(data.nativeEvent.data); alert(JSON.stringify(dataReturned)); } }
Now we have prepared the React Native part where we are going to receive the data.
React
In React, we are going to create a web, for example test.tsx
First, we need to define a new type for Window (required by React Native WebView)
declare global { interface Window { ReactNativeWebView: any; } }
And now, wherever we want to communicate the event, we can:
window.ReactNativeWebView.postMessage("Hello");
Or we can even send JSON objects:
window.ReactNativeWebView.postMessage(JSON.stringify(objToSend));