“The way to get started is to quit talking and begin doing.” – Walt Disney
Overview
In this article, we will learn about how to load data asynchronously and export JSON data to excel in react using the react-csv package.
What is react-csv?
It is a popular npm package to generate a CSV file and download it from given data. It accepts data like array of arrays, an array of literal objects, or strings.
You can use react-csv by npm (node developers) or CDN directly (non-node developers).
The react-csv package includes two components: CSVLink and CSVDownload. In this article, we are going to use the CSVLink component.
Common Props
Both components CSVLink and CSVDownload accepts the following props:
- data: A required property that represents the CSV data. This data can be an array of array, an array of literal objects, or string. This can also be a function that returns any of these things.
- headers: Specifying headers helps to define an order of the CSV fields. The CSV content will be generated accordingly.
- filename: filename is another prop restricted to CSVLink. It specifies the filename of the downloaded CSV.
Package Installation
Using npm,
npm install react-csv –save
Or for non-node developers, you can use CDN directly:
<script src="https://cdn.rawgit.com/abdennour/react-csv/6424b500/cdn/react-csv-latest.min.js" type="text/javascript"></script>
Project Directory
Create a folder within the src folder and name its components. Within the components, folder create two files, one ExportCSV.js, and second UserTable.js.
So, at this point our project directory tree looks like this.
└───src/
├── App.css
├── App.css
├── index.css
├── index.js
└── components/
├── ExportCSV.js
└── UserTable.js
ExportCSV Component
Here, we will use the JSONPlaceholder dummy API to get the list of users using the GET method of Axios. Add the following code in the ExportCSV.js file.
import React, { useState, useEffect } from 'react';
import { CSVLink } from 'react-csv';
import { Button } from '@material-ui/core';
import UserTable from './UserTable';
const axios = require('axios');
const ExportCSV = () => {
const fileName = "users-detail";
const [userData, setUserData] = useState([]);
const [loading, setLoading] = useState(false);
const headers = [
{ label: "Id", key: "id" },
{ label: "Name", key: "name" },
{ label: "Email", key: "email" },
{ label: "Phone", key: "phone" }
];
useEffect(() => {
getUserData();
}, []);
const getUserData = () => {
setLoading(true);
axios.get('https://jsonplaceholder.typicode.com/users')
.then((res) => {
setUserData(res.data);
setLoading(false);
})
.catch((err) => {
console.log("Error: ", err);
setLoading(false);
})
}
return (
<div className='container'>
<Button
variant="contained"
color="primary"
className='export-btn'
>
<CSVLink
headers={headers}
data={userData}
filename={fileName}
style={{ "textDecoration": "none", "color": "#fff" }}
>
{loading ? 'Loading csv...' : 'Export Data'}
</CSVLink>
</Button>
<UserTable headers={headers} userData={userData} />
</div>
);
}
export default ExportCSV;
As you can see, we have prepared an Array of Object and stored it in headers variable. Get user’s data by calling getUserData() method in the useEffect() and store user data in the userData state. Then passed headers, userData, and fileName as Props in the <CSVLink /> component.
Also, passed headers and userData as Props in the <UserTable /> component, just for display data.
UserTable Component
Created this component for the purpose of displaying user data in tabular format. Add the following code content in the UserTable.js file.
import React from 'react';
import { TableContainer, Table, TableHead, TableBody, TableRow, TableCell, Paper } from '@material-ui/core';
const UserTable = ({ headers, userData }) => {
return (
<TableContainer component={Paper}>
<Table sx={{ minWidth: 650 }} size="small" aria-label="a dense table">
<TableHead>
<TableRow>
{headers.map(row => {
return (
<TableCell style={{ "fontWeight": "bold" }}>{row.label}</TableCell>
)
})}
</TableRow>
</TableHead>
<TableBody>
{userData.map(row => (
<TableRow
key={row.id}
>
<TableCell>{row.id}</TableCell>
<TableCell>{row.name}</TableCell>
<TableCell>{row.email}</TableCell>
<TableCell>{row.phone}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
);
}
export default UserTable;
Update App.js File
Replace the contents of the App.js file with the following contents:
import './App.css';
import ExportCSV from './components/ExportCSV';
function App() {
return (
<div className="App">
<h2>Export JSON Data to Excel in React</h2>
<ExportCSV />
</div>
);
}
export default App;
Update App.css File
Replace the App.css file with the following styles:
.App {
text-align: center;
}
.container {
margin: 12px 250px 0px 250px
}
.export-btn {
float: right;
margin-bottom: 10px !important;
}
Output
Run the application by hitting npm start command in the terminal and check the output in the browser.
The downloaded users-detail.csv file looks like the image below,
Summary
In this article, we learned about how to load data asynchronously and export that data in an excel file. Also, discussed the use of react-csv, its components, and common Props of react-csv.
Thanks for reading!!🙂