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
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.
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} />
);
}
}
Just download HTML with fetch(), parse it using fast-html-parser, write result to state and render that state with WebView