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.
1 2 3 4 5 6 7 8 9 10 11 12 13 | [ ] |
Steps to export data to CSV in React
- Create a simple react app
- Install npm package
- Implement logic to download CSV file
- Export to CSV with async data
- 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.
1 | npx create-react-app export-data-to-csv-react |
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.
1 | npm i react-csv |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | import React from 'react'; import { CSVLink } from "react-csv"; const headers = [ { label: "First Name", key: "firstName" }, { label: "Last Name", key: "lastName" }, { label: "Email", key: "email" }, { label: "Age", key: "age" } ]; const data = [ ]; const csvReport = { data: data, headers: headers, filename: 'Clue_Mediator_Report.csv' }; function App() { return ( <div classname="App"> <h3>Export data to CSV in React - <a href="https://cluemediator.com" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h3> <csvlink {...csvreport}>Export to CSV</csvlink> </div> ); } export default App; |
4. Export to CSV with async data
Refer to the following article to export the CSV file by calling an API.
Loading data asynchronously and download CSV using react-csv
5. Output
Run the above code and check the output in the browser.
Demo & Source Code
Github Repository StackBlitz ProjectThat’s it for today.
Thank you for reading. Happy Coding..!!