How to communicate with data between WebViews in React Native.
Published: 2023-06-05 09:43:47

## Introduction

In this post we are going to discuss how we are going to send data from WebView to react native app and from react native app to WebView.

## Sending Data from React Native App to WebView 

First go to the terminal and create a react native application

```
npx react-native init webviewdata
cd webviewdata

```

Now install the package called react-native-webview in this project.

```
npm i react-native-webview
```

## Sending Data from WebView to React Native App

In this section we are going to allow the webview page to send response back to react native app. This will be useful if your React Native application has to deal with certain logic where your website or your webpage has to send some data to your react native app.

In App.js import the React Native WebView package. In this post we are going to create a normal HTML page in the webview and use "<script>" Tags to let the HTML page communicate with the React native app.

In the script tag we are going to call a sendDataToReactNativeApp() function in which we are going to use a window property called window.ReactNativeWebView.postMessage("Message or Data We need to Send"). This function will be called when the user is going to click on the button.

So once this button is clicked we need to capture this particular event in React native with onMessage prop in WebView Component.

We define a function called onMessage and attach this particular function to WebView prop.

```
  function onMessage(data) {
    alert(data.nativeEvent.data);
  }
```

In the WebView Component

```

 <WebView
        scalesPageToFit={false}
        mixedContentMode="compatibility"
        onMessage={onMessage}
        source={{html:'' }}
/>

```

In the source prop use html tags or your own website with the logic u need to implement in your react native app.

Our App.js code will look like below

```
import React from 'react';
import {SafeAreaView, ScrollView, StyleSheet, Text, View} from 'react-native';
import {WebView} from 'react-native-webview';

const App = () => {
  function onMessage(data) {
    alert(data.nativeEvent.data);
  }

  return (
    <SafeAreaView style={{flex: 1}}>
      <WebView
        scalesPageToFit={false}
        mixedContentMode="compatibility"
        onMessage={onMessage}
        source={{
          html: ` 
          <html>
          <head>
            <meta name="viewport" content="width=device-width, initial-scale=1" />
          </head>
          <body
            style="
              display: flex;
              justify-content: center;
              flex-direction: column;
              align-items: center;
            "
          >
            <button
            onclick="sendDataToReactNativeApp()"
              style="
                padding: 20;
                width: 200;
                font-size: 20;
                color: white;
                background-color: #6751ff;
              "
            >
              Send Data To React Native App
            </button>
            <script>
              const sendDataToReactNativeApp = async () => {
                window.ReactNativeWebView.postMessage('Data from WebView / Website');
              };
            </script>
          </body>
        </html>        
`,
        }}
      />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
  },
  highlight: {
    fontWeight: '700',
  },
});

export default App;

```


## Sending Data from React Native App to WebView

Now lets send data from React Native app to WebView.
Create a function called webviewRef and attach it to the WebView component. 

Now create a function called sendDataToWebView and use the below function inside it.

```
function sendDataToWebView() {
    webviewRef.current.postMessage('Data from React Native App');
  }
```

Now inside the "<script>" tag use the window.addEventListener to listen to the event from the react native app.

```
  window.addEventListener("message", message => {
                alert(message.data) 
              });
```

Now App.js will look like below.

```
import React, {useRef} from 'react';
import {
  SafeAreaView,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
} from 'react-native';
import {WebView} from 'react-native-webview';

const App = () => {
  function onMessage(data) {
    alert(data.nativeEvent.data);
  }

  function sendDataToWebView() {
    webviewRef.current.postMessage('Data from React Native App');
  }

  const webviewRef = useRef();

  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={{alignItems: 'center'}}>
        <TouchableOpacity
          onPress={() => sendDataToWebView()}
          style={{
            padding: 20,
            width: 300,
            marginTop: 100,
            backgroundColor: '#6751ff',
            alignItems: 'center',
          }}>
          <Text style={{fontSize: 20, color: 'white'}}>
            Send Data To WebView / Website
          </Text>
        </TouchableOpacity>
      </View>
      <WebView
        ref={webviewRef}
        scalesPageToFit={false}
        mixedContentMode="compatibility"
        onMessage={onMessage}
        source={{
          html: ` 
          <html>
          <head>
            <meta name="viewport" content="width=device-width, initial-scale=1" />
          </head>
          <body
            style="
              display: flex;
              justify-content: center;
              flex-direction: column;
              align-items: center;
            "
          >
            <button
            onclick="sendDataToReactNativeApp()"
              style="
                padding: 20;
                width: 200;
                font-size: 20;
                color: white;
                background-color: #6751ff;
              "
            >
              Send Data To React Native App
            </button>
            <script>
              const sendDataToReactNativeApp = async () => {
                window.ReactNativeWebView.postMessage('Data from WebView / Website');
              };
              window.addEventListener("message", message => {
                alert(message.data) 
              });
            </script>
          </body>
        </html>        
`,
        }}
      />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
  },
  highlight: {
    fontWeight: '700',
  },
});

export default App;


```

To test the app, run npm run android.


## Conclusion

In this post we have discussed how we can send data from WebView to react native app and from react native app to WebView.

All the code involved in this post can be found in the below GitHub link.

https://github.com/Gautham495/React-Native-WebView-Data-Transfer.git