Last updated on Jan 20, 2022 by Suraj Sharma
In this tutorial, you’ll learn how you can create a csv file from async response data in React.
For this tutorial, we will use react-csv npm library.
react-csv
is a popular open source library to generate and download csv files from a response data, with 149k+ weekly downloads.
react-csv
npm install --save react-csv
Create a <ExportCSV />
component, which will do two things,
1) It fetches reponse data from the fake api created using json-server,
//response
{
"results": [
{
"id": 1,
"userDetails": {
"firstName": "Suraj",
"lastName: "Sharma",
"location": "India"
},
"status": "Active"
},
{
"id": 2,
"userDetails": {
"firstName": "John",
"lastName: "Smith",
"location": "Brazil"
},
"status": "Inactive"
}
]
}
2) Next, it generates a csv file using reponse data results and downloads the file.
// ExportCSV.jsx
import React, { useState, useEffect } from react;
import { CSVLink } from react-csv;
const ExportCSV = () => {
const { fileData, setFileData } = useState();
// json key should match the header's key
const [fileHeaders] = useState[{
{label: 'ID', key: 'id'},
{label: 'First Name', key: 'userDetails.firstName'},
{label: 'Last Name', key: 'userDetails.lastName'},
{label: 'Last Name', key: 'userDetails.lastName'},
{label: 'Location', key: 'userDetails.location'},
{label: 'Status', key: 'status'},
}]
};
const handleDataFetch = async() => {
const response = await fetch('https://localhost:5000/results');
const respJSON = await response.json();
setFileData(respJSON)
};
useEffect(()=>{
handleDataFetch();
}, [])
return (
<div>
<h3>Export to CSV</h3>
{fileData?.length &&
<CSVLink
headers={fileHeaders}
data={fileData}
filename="results.csv"
target="_blank"
>
Export
</CSVLink>
}
</div>
);
export default ExportCSV;
react-csv
exports CSVLink
component, which accepts
results stored in fileData
state through data
property,
custom file name 'results.csv' through filename
property, and
csv headers stored in fileHeaders
state through headers
property
Now we will call the ExportCSV
component in the App.jsx
// App.jsx
const App = () => {
return (
<ExportCSV />
);
}
export default App;
In this tutorial, I have covered the basic usage of the react-csv
library, that is to generate and download a csv file on click of a export
link.
For advanced usages, you can visit react-csv examples
Related Solutions
How to change font family of typography in React Material UI
How to Disable a Button when an Input field is Empty in React
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.