How to display XML data In React
Displaying XML data in a React application is a common requirement when dealing with APIs or data sources that provide XML responses. We can use external libraries and techniques to parse and display XML data in a structured and readable format in React.
Xml-js library
The xml-js library is a JavaScript library that provides functions to convert XML data to JSON and vice versa. It offers a simple and efficient way to handle XML data in JavaScript applications, such as ReactJS, by facilitating the conversion and manipulation of XML and JSON formats.
We will follow a few steps given below to display XML data in ReactJS using the xml-js library.
Installing the xml-js library
To get started, we need to install the xml-js library in our React project. Open your terminal and navigate to your project's root directory. Run the following command.
npm install xml-js
Fetching XML data
In the React component, we need to fetch the XML data from an API or a local file. For this example, let's assume we have an XML file named "books.xml" in the public directory of our project.
<?xml version="1.0"?><catalog><book id="bk109"><author>Kress, Peter</author><title>Paradox Lost</title><genre>Science Fiction</genre><price>6.95</price><publish_date>2000-11-02</publish_date><description>After an inadvertant trip through a HeisenbergUncertainty Device, James Salway discovers the problemsof being quantum.</description></book><book id="bk110"><author>O'Brien, Tim</author><title>Microsoft .NET: The Programming Bible</title><genre>Computer</genre><price>36.95</price><publish_date>2000-12-09</publish_date><description>Microsoft's .NET initiative is explored indetail in this deep programmer's reference.</description></book></catalog>
Converting XML to JSON
Once we have the XML data, we can use the xml-js library to convert it to JSON. Import the xml-js library in the component and use the xml2json function to convert the XML data to JSON format. Here's an example.
import React, { useEffect, useState } from 'react';import xmlJs from 'xml-js';const XMLDisplay = () => {const [xmlData, setXmlData] = useState(null);useEffect(() => {fetch('/books.xml') // Replace with the URL or path to your XML data.then((response) => response.text()).then((xmlText) => {const jsonData = xmlJs.xml2json(xmlText, { compact: true, spaces: 4 });setXmlData(JSON.parse(jsonData));}).catch((error) => {console.error('Error fetching XML data:', error);});}, []);return (<div>{xmlData ? (<pre>{JSON.stringify(xmlData, null, 4)}</pre>) : (<p>Loading XML data...</p>)}</div>);};export default XMLDisplay;
Explanation
Line 6: The
useEffecthook is used to create a state variable calledxmlDataand its corresponding setter function,setXmlData. The initial value ofxmlDatais set tonull. TheuseEffecthook is utilized to perform side effects. It takes a callback function as its first argument and an empty dependency array ([]) as the second argument. This ensures that the effect only runs once when the component is mounted.Lines 7–12: Chain promises to handle the response from the fetch request. First, convert the response to text using the
response.text()method. Then, use thexml2jsonfunction from the xml-js library to convert the XML text to JSON format. The resulting JSON data is stored in thejsonDatavariable.Line 11: Parse the
jsonDatavariable usingJSON.parse()to convert it into a JavaScript object. Set the resulting object as the value of thexmlDatastate variable using thesetXmlDatafunction.Lines 18–27:
is used to display either the XML data or a loading message based on the value ofConditional rendering It is the process of displaying different content based on certain conditions or states. xmlData. IfxmlDatais notnull, the JSON data is displayed wrapped in a<pre>tag, usingJSON.stringify()to format it with indentation. IfxmlDataisnull, a "Loading XML data..." message is displayed using a<p>tag.
Rendering the component
To render the XML Display component, we will import it into the main App component or any other component where we want to display the XML data. Simply add <XMLDisplay /> to the JSX code, and the XML data will be fetched, converted, and displayed automatically.
import React from 'react';import ReactDOM from 'react-dom';import './index.css';import XMLDisplay from './App';ReactDOM.render(<React.StrictMode><div className="container"><XMLDisplay /></div></React.StrictMode>,document.getElementById('root'));
Explanation
Line 4: The
XMLDisplaycomponent is imported from the'./App' file. This is where the "Converting XML to JSON" code should be placed.Lines 6–13: The
ReactDOM.render()function is called to render the application's components into the DOM. It takes two arguments: the JSX to be rendered and the target DOM element where the rendered output will be injected.Lines 8–10: The
XMLDisplaycomponent is rendered within the<div className="container">element. This is the main component that will display the XML data or a loading message.
Output
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Palwasha, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
<book id="bk103">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
<description>After the collapse of a nanotechnology
society in England, the young survivors lay the
foundation for a new society.</description>
</book>
<book id="bk104">
<author>Corets, Eva</author>
<title>Oberon's Legacy</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
<description>In post-apocalypse England, the mysterious
agent known only as Oberon helps to create a new life
for the inhabitants of London. Sequel to Maeve
Ascendant.</description>
</book>
<book id="bk105">
<author>Corets, Eva</author>
<title>The Sundered Grail</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-09-10</publish_date>
<description>The two daughters of Maeve, half-sisters,
battle one another for control of England. Sequel to
Oberon's Legacy.</description>
</book>
<book id="bk106">
<author>Randall, Cynthia</author>
<title>Lover Birds</title>
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-09-02</publish_date>
<description>When Carla meets Paul at an ornithology
conference, tempers fly as feathers get ruffled.</description>
</book>
<book id="bk107">
<author>Thurman, Paula</author>
<title>Splish Splash</title>
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-11-02</publish_date>
<description>A deep sea diver finds true love twenty
thousand leagues beneath the sea.</description>
</book>
<book id="bk108">
<author>Knorr, Stefan</author>
<title>Creepy Crawlies</title>
<genre>Horror</genre>
<price>4.95</price>
<publish_date>2000-12-06</publish_date>
<description>An anthology of horror stories about roaches,
centipedes, scorpions and other insects.</description>
</book>
<book id="bk109">
<author>Kress, Peter</author>
<title>Paradox Lost</title>
<genre>Science Fiction</genre>
<price>6.95</price>
<publish_date>2000-11-02</publish_date>
<description>After an inadvertant trip through a Heisenberg
Uncertainty Device, James Salway discovers the problems
of being quantum.</description>
</book>
<book id="bk110">
<author>O'Brien, Tim</author>
<title>Microsoft .NET: The Programming Bible</title>
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-09</publish_date>
<description>Microsoft's .NET initiative is explored in
detail in this deep programmer's reference.</description>
</book>
<book id="bk111">
<author>O'Brien, Tim</author>
<title>MSXML3: A Comprehensive Guide</title>
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-01</publish_date>
<description>The Microsoft MSXML3 parser is covered in
detail, with attention to XML DOM interfaces, XSLT processing,
SAX and more.</description>
</book>
<book id="bk112">
<author>Galos, Mike</author>
<title>Visual Studio 7: A Comprehensive Guide</title>
<genre>Computer</genre>
<price>49.95</price>
<publish_date>2001-04-16</publish_date>
<description>Microsoft Visual Studio 7 is explored in depth,
looking at how Visual Basic, Visual C++, C#, and ASP+ are
integrated into a comprehensive development
environment.</description>
</book>
</catalog>Conclusion
By following the steps given above, we can effectively incorporate XML data into our ReactJS projects. With the ability to convert XML to JSON, we can leverage React's powerful data manipulation and rendering capabilities to create dynamic and interactive user interfaces.
Free Resources