I'm getting html content from an api and I want to render it as a web view in my application.
The webview component is nested in a scrollview because it has some other contents above my render function is something like this:
render() {
var html = '<!DOCTYPE html><html><body>' + this.state.pushEvent.Description + '</body></html>';
return (
<ScrollView>
<View style={styles.recipe}>
<Image source={{uri: this.state.pushEvent.ImageUrl}}
style={styles.imgFull} />
<Text style={styles.title}>{this.state.pushEvent.Title}</Text>
<WebView style={{padding: 20}}
automaticallyAdjustContentInsets={false}
scrollEnabled={false}
html={html}>
</WebView>
</View>
</ScrollView>
);
}
The problem is that my html is just 20pt high that is my padding. Is there a clever way to get the height of the content?
The WebView has default styles. If you want to set height, you also need to add flex: 0 , as stated in the documentation: Please note that there are default styles (example: you need to add flex: 0 to the style if you want to use height property). Save this answer.
React Native provides a Dimensions API that can be used to get the width and the height of the window. From there on, you can compute the available height yourself by subtracting the size of the Toolbar and the TabMenu.
As I wrote on the comment above this is what I came out with, but I'm still thinking that there should be a better solution.
Here is the issue on github I took inspiration from: @hedgerwang answer
In my var html I added a simple script just before the closing body tag, I simply save the height of my html in my document title:
<script>window.location.hash = 1;document.title = document.height;</script>
then I added onNavigationStateChange props in my WebView component with a callback that set a state "height" variable and then set this height to my WebView. As I said, that did the trick, with just a little flahsing while changing the content in the WebView, but I think it's a dirty hack.
At the end I decided to change the api to have something that I don't have to include in a WebView
But maybe this can help, here the full code.
onNavigationStateChange(navState) {
this.setState({
height: navState.title,
});
}
render() {
var html = '<!DOCTYPE html><html><body>' + this.state.pushEvent.Description + '<script>window.location.hash = 1;document.title = document.height;</script></body></html>';
return (
<ScrollView>
<View style={styles.recipe}>
<Image source={{uri: this.state.pushEvent.ImageUrl}}
style={styles.imgFull} />
<Text style={styles.title}>{this.state.pushEvent.Title}</Text>
<WebView style={{padding: 20}}
automaticallyAdjustContentInsets={false}
scrollEnabled={false}
onNavigationStateChange={this.onNavigationStateChange.bind(this)}
html={html}>
</WebView>
</View>
</ScrollView>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With