techStackGuru

React Native WebView


With React Native WebView, you can embed web content in your React Native application.


Install necessary dependencies:

npm install react-native-webview

Link the package to your project:

react-native link react-native-webview

Example

import React from 'react';
import { StyleSheet, View } from 'react-native';
import ReactNativeWebView from 'react-native-webview';

const App = () => {
  return (
    <View style={styles.container}>
      <ReactNativeWebView
        source={{ uri: 'https://www.techstackguru.com' }}
        style={styles.webView}
      />
    </View>
  );
};

const styles = StyleSheet.create(
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  webView: {
    flex: 1,
  },
});

export default App;

Loading Local HTML

import React from 'react';
import { StyleSheet, View } from 'react-native';
import ReactNativeWebView from 'react-native-webview';

const htmlContent = `
<h1>Hello from React Native!</h1>
<p>This is some local HTML content.</p>
`;

const App = () => {
  return (
    <View style={styles.container}>
      <ReactNativeWebView
        source={{ html: htmlContent }}
        style={styles.webView}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  webView: {
    flex: 1,
  },
});

export default App;

Communicating between React Native and WebView:

import React, { useState } from 'react';
import { Button, StyleSheet, Text, View } from 'react-native';
import ReactNativeWebView from 'react-native-webview';

const App = () => {
  const [message, setMessage] = useState('');

  const sendMessageToWebView = () => {
    const message = 'Hello from React Native!';
    webView.injectJavaScript(`window.postMessage('${message}');`);
  };

  const onMessageFromWebView = (event) => {
    const message = event.nativeEvent.data;
    setMessage(message);
  };

  return (
    <View style={styles.container}>
      <ReactNativeWebView
        ref={(ref) => (webView = ref)}
        onMessage={onMessageFromWebView}
        source={{ uri: 'https://your-custom-web-page.com' }}
        style={styles.webView}
      />
      <View style={styles.messageContainer}>
        <Text>Message from WebView:</Text>
        <Text>{message}</Text>
      </View>
      <Button title="Send message to WebView" onPress={sendMessageToWebView} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  webView: {
    flex: 1,
  },
  messageContainer: {
    padding: 10,
    backgroundColor: '#ddd',
  },
});

export default App;