Converting JSON to CSV in React: A DIY Approach
Published: 2024-03-21 02:39:16

Here's a step-by-step breakdown.

1. **Import React**:
   
   ```jsx
   import React from 'react';
   ```

2. **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.
   ```jsx
   const DownloadProducts = ({ elements }) => {
   ```

3. **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".
   ```jsx
   const fileHeaders = [
     'product_name',
     'price',
     'quantity',
     'total_price'
   ];
   ```

4. **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.
   ```jsx
   function convertJSONToCSV(jsonData, columnHeaders) {
     // Function body
   }
   ```

5. **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.
   ```jsx
   function downloadCSV(jsonData, headers) {
     // Function body
   }
   ```

6. **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".
   ```jsx
   return (
     <button
       onClick={() => {
         downloadCSV(elements, fileHeaders);
       }}
     >
       Export Product Data
     </button>
   );
   ```

7. **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.
   ```jsx
   const dummyData = [
     // Sample product data objects
   ];
   ```

8. **Export the Component with Dummy Data**:
   We export the `DownloadProducts ` component with the `dummyData` array passed as props to simulate actual product data.
   ```jsx
   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} />;


```