Hoy os voy a enseñar cómo puedes comunicar una web con React Native directamente usando Javascript y un webview.

Lo primero que tenéis que hacer es instalar la dependencia de webview en React Native:
npm install react-native-webview
Ahora vamos a crear dos códigos, uno será el componente React Native que cargará la URL y quedará a la espera para comunicarse y el otro es el componente HTML que enviará los datos al componente de React Native.
WebView.js
import React, { useState } from "react";
import { View, StyleSheet, Text, Dimensions } from "react-native";
import { WebView } from 'react-native-webview';
//Importar componentes:
var urlCargar = "https://www.....com/test_click.html"
const MapClickView = ({ navigation, route }) => {
const { } = route.params;
return (
<View style={styles.contenedorInicio}>
<View style={styles.contenedor}>
<WebView style={[styles.webview]}
onMessage={onMessage} mixedContentMode="compatibility"
source={{ uri: urlCargar }} />
</View>
</View>
)
};
export default MapClickView;
const styles = StyleSheet.create({
texto: {
fontSize: 30,
color: '#000',
},
contenedorInicio: {
flex: 1,
alignContent: 'center',
alignItems: 'center',
},
webview: {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
flex: 1,
},
contenedorBarra: {
flex: 1,
width: '100%',
},
contenedor: {
flex: 10,
width: '100%',
height: '100%',
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
function onMessage(data) {
alert(data.nativeEvent.data);
}
Se importa y se crea un WebView, además se añade el atributo mixedContentMode=»compatibility» que permite el contenido mixto. Ahora se añade un callBack por el que se comunicará con Javascript del HTML que queramos onMessage={onMessage}.
Los datos se obtendrán en la función:
function onMessage(data) {
alert(data.nativeEvent.data);
}
Ahora vamos a crear el componente HTML qué enviará el dato.
<!DOCTYPE html
PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html>
<head>
<title>My Title</title>
</head>
<body>
<input type='button' value='Click me' onclick='enviarMensaje()' />
</body>
<script>
function enviarMensaje() {
window.ReactNativeWebView.postMessage("Datos enviados");
}
</script>
</html>
En este caso he creado un botón que invoca la función enviarMensaje(); con onclick=’enviarMensaje()’
En esta función he añadido el método que enviará el dato al componente React Native:
window.ReactNativeWebView.postMessage(«Datos enviados»);
Esto comunicará con el componente React Native creado.
Recuerda que puedes enviar un JSON usando JSON.stringify({}) para enviar y JSON.parse(«{}») para recibir.

Ingeniero en Informática, Investigador, me encanta crear cosas o arreglarlas y darles una nueva vida. Escritor y poeta. Más de 20 APPs publicadas y un libro en Amazon.