Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to render dynamic content from back-end that has html tags in react native

I have created an app that uses woo-commerce as back-end, the problem is many of the attributes of products that I receive from back-end are in html, when I tried to render it in it treated everything as text and as a result the whole string got printed to the screen with all the html tags which is not the desired result .

Is there any trick except for the Web-View to solve this problem?

like image 973
Ammar Tariq Avatar asked Dec 22 '25 03:12

Ammar Tariq


1 Answers

For me the best way to render HTML code is to use a library called react-native-htmlview.

This is a simple example:

import React, {Component} from 'react';
import {
  View,
  StyleSheet,
} from 'react-native';
import HTMLView from 'react-native-htmlview';

class App extends Component {
  state = {
    html: '<p>Some Dummy <b>HTML</b> code</p>'
  }

  render() {
    return (
        <View style={styles.container}>
          <HTMLView
              value={this.state.html}
              stylesheet={htmlStyleSheet}
          />
        </View>
    );
  }
}

const htmlStyleSheet = StyleSheet.create({
  p: {
    color: 'red'
  },
  b: {
    color: 'black'
  }
})

const styles = StyleSheet.create({
  container: {
    paddingTop: 20,
  }
})

export default App;

For more information:

https://github.com/archriss/react-native-render-html

Another option is to use WebView with source prop:

https://facebook.github.io/react-native/docs/webview

import React, { Component } from 'react';
import { WebView } from 'react-native';

class MyInlineWeb extends Component {
  render() {
    return (
      <WebView
        originWhitelist={['*']}
        source={{ html: '<h1>Hello world</h1>' }}
      />
    );
  }
}
like image 154
Naoufal Avatar answered Dec 23 '25 16:12

Naoufal