Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 573
Dmitry Petukhov Avatar asked Jul 13 '16 06:07

Dmitry Petukhov


2 Answers

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

like image 114
Dmitry Petukhov Avatar answered Sep 27 '22 15:09

Dmitry Petukhov


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.

like image 30
ljmocic Avatar answered Sep 27 '22 15:09

ljmocic