Home > Software design >  How to display xml to html in react-native?
How to display xml to html in react-native?

Time:06-07

I had XML documents that contains html content. How do I render xml to html in react native.I've even tried with react also it was failing.

import React, { useEffect, useRef, useState } from 'react';
import { View } from 'react-native';
import { useWindowDimensions } from 'react-native';
import axios from 'axios';
import { DOMParser } from 'xmldom';
import RenderHtml from 'react-native-render-html';

export default function App() {
  const { width } = useWindowDimensions();
  const ref = useRef(null);
  const [xml, setXml] = useState(`
  <p style='text-align:center;'>
    Hello World!
  </p>`);

  const source = {
    html: xml,
  };

  const appendToNode = (node, content) => {
    node.innerHTML  = content;
  };

  useEffect(() => {
    const DOMParse = new DOMParser();
    let xmlDoc;
    axios
      .get(
        'https://uhf.microsoft.com/en-US/shell/xml/MSIrelandsFuture?headerId=MSIrelandsFutureHeader&footerid=MSIrelandsFutureFooter',
        {
          'Content-Type': 'application/xml; charset=utf-8',
        },
      )
      .then(response => {
        xmlDoc = DOMParse.parseFromString(response.data, 'text/xml');
        appendToNode(
          document.head,
          xmlDoc.querySelector('cssIncludes').textContent,
        );
        appendToNode(
          document.head,
          xmlDoc.querySelector('javascriptIncludes').textContent,
        );
        appendToNode(
          ref.current,
          xmlDoc.querySelector('headerHtml').textContent,
        );
        appendToNode(
          ref.current,
          xmlDoc.querySelector('footerHtml').textContent,
        );
      })
      .catch(err => console.log(err));
  }, []);
  console.log('REFFFF', ref);
  return (
    <View style={{ flex: 1 }}>
      <View style={{ marginTop: 79 }} />
      <RenderHtml contentWidth={width} source={source} />
    </View>
  );
}

Think is convert the XML to html and render html in react native using react-native-render-html or any third party libraries.

Thanks Advance :)

CodePudding user response:

The React Native docs currently recommend React Native WebView:

<WebView
    originWhitelist={['*']}
    source={{ html: '<p>Here I am</p>' }}
/>

https://github.com/react-native-webview/react-native-webview

If you don't want to embed a WebView, there are also third party libraries to render HTML into native views:

react-native-render-html react-native-htmlview

CodePudding user response:

To convert the xml to html you use parseXML function and after do display we can use webview from package "react-native-webview" to display the content like below.

fetch('url')
  .then(data=>{
    data = $.parseXML(data);
    console.log(data);
  })
  .catch((err)=>{
    console.log(err);
  });
  • Related