How do I parse an HTML file in React Native?

后端 未结 3 835
借酒劲吻你
借酒劲吻你 2021-02-09 21:49

How can I get an HTML file from file system and parse specific elements from it.

For example, given the html snippet below, how can I extract the table content and rende

相关标签:
3条回答
  • 2021-02-09 22:34

    Get html with fetch() and parse with react-native-html-parser, process and display with WebView.

    import DOMParser from 'react-native-html-parser';
    
    fetch('http://www.google.com').then((response) => {
       const html = response.text();    
       const parser = new DOMParser.DOMParser();
       const parsed = parser.parseFromString(html, 'text/html');
       parsed.getElementsByAttribute('class', 'b');
    });
    

    P.S. fast-html-parser from other answers didn't work for me. I got multiple errors while installing it with react-native 0.54.

    0 讨论(0)
  • 2021-02-09 22:37

    I would recommend using this library: react-native-htmlviewer. It takes html and renders it as native views. You can also customize the way elements get rendered.

    // only render the <table> nodes in your html
    function renderNode(node, index, siblings, parent, defaultRenderer) {
      if (node.name !== 'table'){
        return (
          <View key={index}>
            {defaultRenderer(node.children, parent)}
          </View>
        )l
      }
    
    }
    
    // your html
    const htmlContent = `<html></html>`;
    
    class App extends React.Component {
      render() {
        return (
          <HTMLView value={htmlContent} renderNode={renderNode} />
        );
      }
    }
    
    0 讨论(0)
  • 2021-02-09 22:43

    Just download HTML with fetch(), parse it using fast-html-parser, write result to state and render that state with WebView

    0 讨论(0)
提交回复
热议问题