Today we are going to learn how we can load an XML file into our React project to display the data.

The first thing we are going to do is to install the necessary library, in this case, we will use xml2js.
npm install xlsx
Once installed, we are going to create the component that will be responsible for loading our XML file.
XMLLoader.js
// xmlLoader.js
import parseString from 'xml2js';
async function loadXMLFile(filePath) {
try {
const response = await fetch(filePath);
const xmlText = await response.text();
const xmlObject = await parseXML(xmlText);
return xmlObject;
} catch (error) {
console.error('Error loading XML file:', error);
throw error;
}
}
function parseXML(xmlText) {
return new Promise((resolve, reject) => {
parseString(xmlText, (error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
}
export default loadXMLFile;
In TypeScript:
// xmlLoader.ts
import { parseString } from 'xml2js';
async function loadXMLFile(filePath: string): Promise<any> {
try {
const response = await fetch(filePath);
const xmlText = await response.text();
const xmlObject = await parseXML(xmlText);
return xmlObject;
} catch (error) {
console.error('Error loading XML file:', error);
throw error;
}
}
function parseXML(xmlText: string): Promise<any> {
return new Promise((resolve, reject) => {
parseString(xmlText, (error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
}
export default loadXMLFile;
Explanation:
loadXMLFile: This function usesfetchto fetch the XML file content and then callsparseXMLto parse that content and return it as a JavaScript object.parseXML: This function uses thexml2jslibrary to convert the XML text into a JavaScript object.
And to use it, we’ll do the following:
Of course, I will divide point 3 into smaller sections and explain each step:
Import dependencies and xmlLoader file
// YourComponent.tsx
import React, { useEffect, useState } from 'react';
import loadXMLFile from './xmlLoader';
Explanation:
- We import the necessary dependencies (
React,useEffect,useState) and theloadXMLFilefunction we previously created.
Define the component and state:
function YourComponent() {
// State to store XML data after loading
const [xmlData, setXmlData] = useState<any>(null);
Explanation:
- We create a functional component called
YourComponent. - We use the
useStatehook to define a state calledxmlData, which will store the XML data after loading. Initially, it is set tonull.
Use the useEffect hook to load the XML when the component mounts:
useEffect(() => {
async function fetchData() {
try {
// Call the function to load the XML file
const result = await loadXMLFile('path/to/file.xml');
setXmlData(result);
} catch (error) {
// Handle errors, for example, display an error message to the user
console.error('Error loading XML file:', error);
}
}
// Call the data loading function when the component mounts
fetchData();
}, []); // The second argument of useEffect ensures it only runs once when the component mounts
Explanation:
- We use the
useEffecthook to perform side effects in the component, such as loading the XML file. - Inside
useEffect, we define an asynchronous function calledfetchData. fetchDatacalls theloadXMLFilefunction to load the XML file and updates the state with the obtained data.- Any errors during loading are handled in the
catchblock.
Display a loading message if the data hasn’t been loaded yet
if (!xmlData) {
return <div>Loading...</div>;
}
Explanation:
- We check if the XML data hasn’t been loaded yet (
xmlDataisnull). - If so, we display a loading message. This prevents the rest of the component from rendering before the data is ready.
Do something with the XML data (optional):
// Do something with the XML data, for example, print it to the console
console.log(xmlData);
// Render the XML data in your component (you can customize this according to your needs)
return (
<div>
{/* Render the XML data in your component */}
</div>
);
}
export default YourComponent;
Explanation:
- In this step, we log the XML data to the console using
console.log(xmlData). You can perform any operations you need with the data here. - Then, you can customize the return part (
return) to render the XML data in your component according to your specific needs.
The complete code would be:
// YourComponent.tsx
import React, { useEffect, useState } from 'react';
import loadXMLFile from './xmlLoader';
function YourComponent() {
// State to store XML data after loading
const [xmlData, setXmlData] = useState<any>(null);
// Effect to load the XML file when the component mounts
useEffect(() => {
async function fetchData() {
try {
// Call the function to load the XML file
const result = await loadXMLFile('path/to/file.xml');
setXmlData(result);
} catch (error) {
// Handle errors, for example, display an error message to the user
console.error('Error loading XML file:', error);
}
}
// Call the data loading function
fetchData();
}, []); // The second argument of useEffect ensures it only runs once when the component mounts
// Display a loading message if the XML data hasn't been loaded yet
if (!xmlData) {
return <div>Loading...</div>;
}
// Do something with the XML data, for example, print it to the console
console.log(xmlData);
// Render the XML data in your component
return (
<div>
{/* Render the XML data in your component */}
</div>
);
}
export default YourComponent;
