Skip to content Skip to sidebar Skip to footer

Updating Webview Javascript In React Native

I'm having trouble updating my WebView values based on user input in React Native. I'm trying to make charts in WebView using D3.js, and the chart displayed is depending on user in

Solution 1:

I was able to do this using messages instead of injected javascript. I would like to recommend people to just use a library such as victory-charts or use react-art to render svg paths instead, as webviews are just not optimal for this type of problem (d3 charts in React Native).

    // @flow
'use strict';
import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  Image,
  Text,
  TouchableHighlight,
  WebView
} from 'react-native';

export default class WebViewTest extends Component {

  constructor(props) {
    super(props);
    this.state = {
    timesClicked : 0
  };
  this._onPressButton = this._onPressButton.bind(this);
  }

  _onPressButton() {
    let timesClicked = this.state.timesClicked;
    timesClicked++;
    console.log(timesClicked + " Clicked ");
    this.setState({
      timesClicked: timesClicked
    });
    this.refs.myWebView.postMessage("This is my land times " + timesClicked);
  }

  render() {
    let html = `
        <div id="content">
            This is my name
        </div>
        <script>
          document.addEventListener('message', function(e) {
            document.getElementById("content").innerHTML = e.data;
          });
        </script>
    `;

    return (
        <View style={styles.container}>
          <TouchableHighlight onPress={this._onPressButton}>
            <Text>Press me to increase click</Text>
          </TouchableHighlight>
          <Text>React Native times clicked: {this.state.timesClicked}</Text>
            <WebView
                style={styles.webView}
                source={{html : html}}
                ref="myWebView"
                javaScriptEnabledAndroid={true}
                onMessage={this.onMessage}
            >
            </WebView>
        </View>
    );
  }
}

let styles = StyleSheet.create({
container: {
    flex: 1,
    backgroundColor: '#fff',
    margin: 30
},
webView: {
    backgroundColor: '#fff',
    height: 350,
}
});

Post a Comment for "Updating Webview Javascript In React Native"