How to load dynamic html string in webview

I want to load a dynamic html string in webview when an asynchronous web service request is complete. How can i do this?

 <WebView source={{html: dynamichtml}}/>

 getMoviesFromApiAsync()
 {
   return fetch('*****some url*****')
   .then((response) => response.json())
   .then((responseJson) => {
     this.setState({isLoading: false, jsonData: responseJson});
     this.getDataFromServer(responseJson);
     return responseJson;
   })
   .catch((error) => {
     console.error(error);
   });

}

 getDataFromServer(responseJson)
 {
   var a ='ravi';
   var b = 'chennai';
   var commonHtml = `my name is ${a} from ${b}`;
   <WebView source={{html: commonHtml}}/>  // not working
 }
+4
source share
1 answer

You can accomplish this, for example. rendering delay WebViewuntil the request is completed:

constructor(props) {
  super(props);

  this.state = {
    commonHtml = ''
  };
}

componentDidMount() {
  getMoviesFromApiAsync();
}

getMoviesFromApiAsync() {
  fetch('*****some url*****')
  .then((response) => response.json())
  .then((responseJson) => {
    // Assuming responseJson.data.nameA and responseJson.data.nameB exist
    const { nameA, nameB } = responseJson.data;
    this.setState({commonHtml: `my name is ${nameA} from ${nameB}`});
  })
  .catch((error) => {
    console.error(error);
  });
}

render() {
  const commonHtml = { this.state };

  return (
    <View>
      {commonHtml ?
        <WebView style={{width: 200, height: 200}} source={{html: commonHtml}} /> :
        (
          <View>
            <Text>Loading</Text>
          </View>
        )
      }
    </View>
  );
}

This example WebViewonly displays if there is some content in this.state.commonHtml.

In fact, the Trojan is not even needed if you do not want to do anything. You can just do

render() {
  return (
    <WebView style={{width: 200, height: 200}} source={{html: this.state.commonHtml}} />
  );
}

and setStatecauses re-visualization upon change this.state.commonHtml.

0
source

Source: https://habr.com/ru/post/1674965/


All Articles