Rendering raw HTML(Hyper Text Markup Language) code in both android and iOS application can be possible through WebView component. Because sometimes developer needs to parse Raw HTML Code come inside JSON into Text component. So in this tutorial we would going to Render Raw HTML Code in React Native App Using WebView component using source={{ html: YourHTMLcode}} prop.
Contents in this project Render Raw HTML Code in React Native App Using WebView :
1. Import StyleSheet, WebView and Platform component in your project.
1 2 3 |
import React, { Component } from 'react'; import { StyleSheet, WebView, Platform} from 'react-native'; |
2. Create a Var named as HtmlCode inside render’s block and define your all HTML code in that variable like i did in below code. You need to use +(Plus) symbol after every line to connect each line code.
1 2 3 4 5 6 7 8 9 10 11 12 |
render() { var HtmlCode = '<h1> h1 Heading Tag</h1>' + '<p> Sample Paragraph Tag </p>' + '<img src="https://reactnativecode.com/wp-content/uploads/2017/05/react_thumb_install.png" alt="Image" width="250" height="150" >' ; return ( ); } |
3. Call the HtmlCode var into source prop of WebView with html .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
render() { var HtmlCode = '<h1> h1 Heading Tag</h1>' + '<p> Sample Paragraph Tag </p>' + '<img src="https://reactnativecode.com/wp-content/uploads/2017/05/react_thumb_install.png" alt="Image" width="250" height="150" >' ; return ( <WebView style={styles.WebViewStyle} javaScriptEnabled={true} domStorageEnabled={true} source={{ html: HtmlCode }} /> ); } |
4. Create custom Style class :
1 2 3 4 5 6 7 8 9 10 11 12 |
const styles = StyleSheet.create( { WebViewStyle: { justifyContent: 'center', alignItems: 'center', flex:1, marginTop: (Platform.OS) === 'ios' ? 20 : 0 } }); |
5. Complete source code for App.js File :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import React, { Component } from 'react'; import { StyleSheet, WebView, Platform} from 'react-native'; export default class MainActivity extends Component { render() { var HtmlCode = '<h1> h1 Heading Tag</h1>' + '<p> Sample Paragraph Tag </p>' + '<img src="https://reactnativecode.com/wp-content/uploads/2017/05/react_thumb_install.png" alt="Image" width="250" height="150" >' ; return ( <WebView style={styles.WebViewStyle} javaScriptEnabled={true} domStorageEnabled={true} source={{ html: HtmlCode }} /> ); } } const styles = StyleSheet.create( { WebViewStyle: { justifyContent: 'center', alignItems: 'center', flex:1, marginTop: (Platform.OS) === 'ios' ? 20 : 0 } }); |
Screenshot in Android device :
HTML raw code is not rendering in iOS. What could be the reason for this ?
Kabeer you need to update you react native project.
Content is not displaying without giving height to the style. How can i adjust it with content size?
Akhil simply put height 100% .