Search code examples
javascripthtmlreact-nativehtml-parsing

How do I parse an HTML file in React Native?


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 render it?

<html>
<div>
  <h1>header</h1>
  <table id="a" border="1">
    <th>Number</th>
    <th>content A</th>
    <th>contetn A</th>
    <th>content A</th>
    <tr>
      <td>1</td>
      <td>a</td>
      <td>a</td>
      <td>a</td>
    </tr>
    <th>Number</th>
    <th>content B</th>
    <th>content B</th>
    <th>content B</th>

    <tr>
      <td>1</td>
      <td>b</td>
      <td>b</td>
      <td>b</td>
    </tr>
  </table>
</div>
<br>
<footer>footer</footer>

</html>


Solution

  • 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} />
        );
      }
    }