Converting JSON to CSV in React: A DIY Approach

cybercop

Adan Kalla

Posted on March 21, 2024

Converting JSON to CSV in React: A DIY Approach

Here's a step-by-step breakdown.

  1. Import React:
   import React from 'react';
Enter fullscreen mode Exit fullscreen mode
  1. Define the DownloadProducts Component: Create a functional component named DownloadProducts, which takes elements as props. This component is responsible for converting the provided data into a CSV file and enabling users to download it.
   const DownloadProducts = ({ elements }) => {
Enter fullscreen mode Exit fullscreen mode
  1. 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'
   ];
Enter fullscreen mode Exit fullscreen mode
  1. 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
   }
Enter fullscreen mode Exit fullscreen mode
  1. 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
   }
Enter fullscreen mode Exit fullscreen mode
  1. Return Button Component for CSV Export: The DownloadProducts component returns a button that, when clicked, triggers the downloadCSV function. The button text reads "Export Product Data".
   return (
     <button
       onClick={() => {
         downloadCSV(elements, fileHeaders);
       }}
     >
       Export Product Data
     </button>
   );
Enter fullscreen mode Exit fullscreen mode
  1. 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
   ];
Enter fullscreen mode Exit fullscreen mode
  1. Export the Component with Dummy Data: We export the DownloadProducts component with the dummyData array passed as props to simulate actual product data.
   export default () => < DownloadProducts elements={dummyData} />;
Enter fullscreen mode Exit fullscreen mode

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} />;


Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
cybercop
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.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024