Export data to CSV in React

In this react article, we’ll show you how to export data to CSV in React using the package. When we are working with a table we may need to export the table data to a CSV file using ReactJS.

Here, we will create a react application to export the list of records in CSV file and download CSV file on click of the button. Therefore we’ll use the NPM Package to exporting the data on single click.

For a quick demo, we are going to use the following data which can be considered as a table record.

Steps to export data to CSV in React

  1. Create a simple react app
  2. Install npm package
  3. Implement logic to download CSV file
  4. Export to CSV with async data
  5. Output

1. Create a simple react app

Let’s create a simple react application using create-react-app. Run the following command to create a react app.

Refer to the link for Create React Application.

2. Install npm package

To download records in a CSV file, we will use the react-csv npm package. Run the following command to install the react-csv package.

3. Implement logic to download CSV file

Now we will define two different variables data and headers where we will store the list of records in the data variable and store the header of the CSV file in the headers variable.

Let’s import the CSVLink from the react-csv package and use it as a link to export the CSV file.

App.js

4. Export to CSV with async data

If you want to export the CSV file by calling API then you have to set the asyncOnClick property to the true and handle the onClick event for downloading CSV file.

The onClick event provides two different parameters event & done method. Once we fetch the records from the API call then we have to execute done() method and If we want to cancel the process then execute done(false).

AsyncCSV.js

5. Output

Run the above code and check the output in the browser.

Output - Export data to CSV in React - Clue Mediator
Output – Export data to CSV in React – Clue Mediator

Demo & Source Code

Github Repository StackBlitz Project

That’s it for today.
Thank you for reading. Happy Coding..!!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *