Search code examples
reactjsxml2js

How to parse input xml data to json in react with xml2js?


I am trying to parse the input xml data to json in react with the help of xml2js.

import React, { useState } from "react";
import xml2js from "xml2js";

function Parser() {
  const [xmlData, setXmlData] = useState({});
  let parser = new xml2js.Parser();
  parser.parseString(
    `<email>
       <to>Test</to>
       <from>Test1</from>
       <heading>Test email</heading>
       <body>Email regards to xml data parsing in React</body>
       </email>`,
    function (err, result) {
      console.log(result);
      if (result) {
        setXmlData(result);
        return;
      }
      return;
    }
  );
  return (
    <div>
      Parse XML using ReactJs
      {JSON.stringify(xmlData)}
    </div>
  );
}

export default Parser;

But I am getting unlimited re render error. Can anyone help on this ?

Thanks in advance


Solution

  • Since parseString is an asynchronous API, you will need to call it in an useEffect hook with the input data set as a dependency to avoid it being re-re-re-re-...-called on each render.

    I also moved the input data to a prop here, for reusability.

    import React, { useState } from "react";
    import xml2js from "xml2js";
    
    function Parser({ inputData }) {
      const [xmlData, setXmlData] = React.useState(null);
      React.useEffect(() => {
        const parser = new xml2js.Parser();
        parser.parseString(inputData, function (err, result) {
          setXmlData(result);
        });
      }, [inputData]);
      return (
        <div>
          Parse XML using ReactJs
          {JSON.stringify(xmlData)}
        </div>
      );
    }
    
    export default Parser;
    
    <Parser inputData={`<email>
           <to>Test</to>
           <from>Test1</from>
           <heading>Test email</heading>
           <body>Email regards to xml data parsing in React</body>
           </email>`}
    />