ReactJS(PWA), React Native app integration with both way communication

  1. Create RN CLI app and add react native web view
  2. Create ReactJS PWA
  3. Create communication functionality between mobile and PWA
  4. Simple implementation with added security (web view authentication)

1. Create RN app and add react native web view

Refer official documentation to create react native CLI app and add the react-native-webview.

2. Create ReactJS PWA

A good guide to create PWA using : PWA React tutorial: How to Build PWA with React in 5 Steps

3. Create communication functionality between mobile and PWA

Here it uses the post messages to do the communication between two front ends. So it’s good have some understanding regarding the web postMessage() method.

  • PWA to Mobile
// Listener function
const handleMessage = message => {
Alert.alert(message.nativeEvent.data);
};


// Webview component
<WebView
source={{uri: STATIC_WEB_URL}}
startInLoadingState={true}
renderLoading={() => <ActivityIndicator />}
onMessage={handleMessage}
onError={syntheticEvent => {
const {nativeEvent} = syntheticEvent;
console.warn('WebView error: ', nativeEvent);
}}
/>

const sendMessage = () => {
window.ReactNativeWebView.postMessage('Hi from PWA');
};

/**
* window.ReactNativeWebView.postMessage accepts one argument, data
* which will be available on the event object, event.nativeEvent.data. data must be a string
*/

// Button action to send message
const handleMessage = message => {
Alert.alert(message.nativeEvent.data);
};

// Button component
<button onClick={sendMessage}>
Say Hi
</button>
PWA to Mobile Message
  • Now let’s see the vice versa communication, Mobile to PWA
window.addEventListener('message', (e) => {
alert(JSON.stringify(e.data));
});
  1. Send message onLoad of web view
  2. Send messages based on user interactions (Ex. button click)
// Variable to hold webview ref
const webViewRef = useRef(null);

<WebView
source={{uri: STATIC_WEB_URL}}
startInLoadingState={true}
renderLoading={() => <ActivityIndicator />}
onMessage={handleMessage}
ref={webViewRef} // Assign webview ref to the `webViewRef` variable while initial rendering
onError={syntheticEvent => {
const {nativeEvent} = syntheticEvent;
console.warn('WebView error: ', nativeEvent);
}}
/>
// Send message function
const sendMessage = () => {
if (webViewRef.current) {
webViewRef.current.postMessage('Hi from Mobile');
}
};

// Button component to send message
<Button title={'Hello'} onPress={sendMessage} />
Mobile to PWA message

4. Simple implementation with added security (web view authentication)

To be continued …….. (will update the link later 😊😊)

--

--

el173 — Focus on BigPicture; Syntax doesn’t matter

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store