Converting JSON to CSV in React: A DIY Approach
Adan Kalla
Posted on March 21, 2024
Here's a step-by-step breakdown.
- Import React:
import React from 'react';
-
Define the DownloadProducts Component:
Create a functional component named
DownloadProducts
, which takeselements
as props. This component is responsible for converting the provided data into a CSV file and enabling users to download it.
const DownloadProducts = ({ elements }) => {
-
Define Column Headers for CSV:
Define an array
fileHeaders
containing the column headers for the CSV file. In this case, we have "product_name", "price", "quantity", and "total_price".
const fileHeaders = [
'product_name',
'price',
'quantity',
'total_price'
];
-
Convert JSON to CSV Function:
Define a function
convertJSONToCSV
that converts JSON data to a CSV-formatted string. It takes the JSON data and column headers as input and returns the CSV string.
function convertJSONToCSV(jsonData, columnHeaders) {
// Function body
}
-
Function to Initiate CSV Download:
Define a function
downloadCSV
to initiate the download of the CSV file when the user clicks a button. It takes JSON data and headers as input, converts the data to CSV format, creates a Blob object, and triggers the download.
function downloadCSV(jsonData, headers) {
// Function body
}
-
Return Button Component for CSV Export:
The
DownloadProducts
component returns a button that, when clicked, triggers thedownloadCSV
function. The button text reads "Export Product Data".
return (
<button
onClick={() => {
downloadCSV(elements, fileHeaders);
}}
>
Export Product Data
</button>
);
-
Define Dummy JSON Data:
We define a sample array
dummyData
containing objects representing product information. Each object has "product_name", "price", "quantity", and "total_price" fields.
const dummyData = [
// Sample product data objects
];
-
Export the Component with Dummy Data:
We export the
DownloadProducts
component with thedummyData
array passed as props to simulate actual product data.
export default () => < DownloadProducts elements={dummyData} />;
Full Code:
import React from 'react';
// Define the DownloadProducts component
const DownloadProducts = ({ elements }) => {
// Define column headers for CSV
const fileHeaders = [
'product_name',
'price',
'quantity',
'total_price'
];
// Function to convert JSON to CSV string
function convertJSONToCSV(jsonData, columnHeaders) {
// Check if JSON data is empty
if (jsonData.length === 0) {
return '';
}
// Create headers string
const headers = columnHeaders.join(',') + '\n';
// Map JSON data to CSV rows
const rows = jsonData
.map((row) => {
// Map each row to CSV format
return columnHeaders.map((field) => row[field] || '').join(',');
})
.join('\n');
// Combine headers and rows
return headers + rows;
}
// Function to initiate CSV download
function downloadCSV(jsonData, headers) {
const csvData = convertJSONToCSV(jsonData, headers);
// Check if CSV data is empty
if (csvData === '') {
alert('No data to export');
} else {
// Create CSV file and initiate download
const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.setAttribute('download', 'product_data.csv');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
// Render the button for CSV export
return (
<button
onClick={() => {
downloadCSV(elements, fileHeaders);
}}
>
Export Product Data
</button>
);
};
// Sample JSON data for products
const dummyData = [
{
"product_name": "Widget",
"price": 50,
"quantity": 2,
"total_price": 100
},
{
"product_name": "Gadget",
"price": 100,
"quantity": 1,
"total_price": 100
},
{
"product_name": "Tool",
"price": 75,
"quantity": 3,
"total_price": 225
},
{
"product_name": "Accessory",
"price": 25,
"quantity": 4,
"total_price": 100
},
{
"product_name": "Equipment",
"price": 200,
"quantity": 1,
"total_price": 200
}
];
// Export the component with sample data
export default () => <DownloadProducts elements={dummyData} />;
💖 💪 🙅 🚩
Adan Kalla
Posted on March 21, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.