top of page
dp.jpg

Hi, thanks for stopping by!

Hope you are getting benefitted out of these articles. Don't forget to subscribe to the Newsletter where we will serve you with the curated content right at your mailbox.

Let the posts
come to you.

Sponsor the Author.

Download CSV in React JS from JSON Array: Step-by-Step Guide

There are many times when you have to download the data in CSV format. This feature is usually required whenever we want to export/import the data.



let us suppose on your React/Angular application you have a page, showcasing the data. Sometimes your operations team wants to download and share the data with the merchant. For the same purpose, we can write the same logic.


React JS Code for the same.

import React from 'react';
import { Parser } from 'json2csv';

const jsonData = [
  { name: 'John Doe', age: 28, city: 'New York' },
  { name: 'Anna Smith', age: 22, city: 'London' },
  { name: 'Peter Jones', age: 35, city: 'Paris' }
];

const downloadCSV = () => {
  const parser = new Parser();
  const csv = parser.parse(jsonData);
  
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);

  link.setAttribute('href', url);
  link.setAttribute('download', 'data.csv');
  link.style.visibility = 'hidden';

  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

const CsvDownloader = () => {
  return (
    <div>
      <button onClick={downloadCSV}>Download CSV</button>
    </div>
  );
};

export default CsvDownloader;

Explanation

Sure, let's go through the code step-by-step:


1. Import React and Parser from json2csv:



    import React from 'react';
	import { Parser } from 'json2csv';

- React: Importing the core React library to use React components and hooks.

- Parser: Importing the `Parser` class from the `json2csv` library, which will be used to convert JSON data to CSV format.


2. Define JSON Data:


    const jsonData = [
      { name: 'John Doe', age: 28, city: 'New York' },
      { name: 'Anna Smith', age: 22, city: 'London' },
      { name: 'Peter Jones', age: 35, city: 'Paris' }
    ];

- jsonData: An array of objects, where each object represents a person's details including their name, age, and city.


3. Function to Download CSV:

const downloadCSV = () => {
      const parser = new Parser();
      const csv = parser.parse(jsonData);
      const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      link.setAttribute('href', url);
      link.setAttribute('download', 'data.csv');
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
};

- downloadCSV: A function that handles the process of converting the JSON data to CSV and initiating the download.

- parser = new Parser(): Creates a new instance of the `Parser` class.

- csv = parser.parse(jsonData): Converts the `jsonData` array into CSV format.

- blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' }): Creates a new `Blob` object containing the CSV data.

- link = document.createElement('a'): Creates a new anchor (`<a>`) element.

- url = URL.createObjectURL(blob): Generates a temporary URL for the `Blob` object.

- link.setAttribute('href', url): Sets the `href` attribute of the anchor element to the temporary URL.

- link.setAttribute('download', 'data.csv'): Sets the `download` attribute of the anchor element to specify the filename for the downloaded CSV.

- link.style.visibility = 'hidden': Hides the anchor element.

- document.body.appendChild(link): Appends the anchor element to the document body.

- link.click(): Programmatically clicks the anchor element to trigger the download.

- `document.body.removeChild(link)`: Removes the anchor element from the document body.


4. Create CsvDownloader Component:


const CsvDownloader = () => {
      return (
        <div>
          <button onClick={downloadCSV}>Download CSV</button>
        </div>
      );
    };
export default CsvDownloader;

- CsvDownloader: A functional React component that renders a button.

- The button has an `onClick` event handler that calls the downloadCSV function when clicked.

- The component is exported as the default module export.


 

Summary


- The component renders a button that, when clicked, triggers the conversion of predefined JSON data into CSV format.

- It then programmatically creates a temporary link to the CSV file and simulates a click on that link to initiate the download.

- The temporary link is removed from the document after the click to clean up.

25 views

Recent Posts

See All

Comments


bottom of page