How to add Export to CSV button in react table.

Manish Mandal
How To React
Published in
4 min readMay 22, 2023

--

Today in this tutorial we will see how we can add an export to CSV button in React Table. React table is a powerful library available for React through which we can create complex tables in React Applications. One important feature that is often needed is the functionality to export table data in CSV files. Let’s see how we can do that in this article.

Step 1: Install Required Packages

First, we will need to install the required package for creating the functionality. Open your terminal and run the below command.

npm install react-table react-csv

Step 2: Create a dummy JSON file for data.

We need to create a JSON file that will be used to create a table in react application. So open your src directory and inside that create a data folder and create a new file with the name users.json and paste the below data in it.

[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org"
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna@melissa.tv",
"phone": "010-692-6593 x09125",
"website": "anastasia.net"
},
{
"id": 3,
"name": "Clementine Bauch",
"username": "Samantha",
"email": "Nathan@yesenia.net",
"phone": "1-463-123-4447",
"website": "ramiro.info"
},
{
"id": 4,
"name": "Patricia Lebsack",
"username": "Karianne",
"email": "Julianne.OConner@kory.org",
"phone": "493-170-9623 x156",
"website": "kale.biz"
},
{
"id": 5,
"name": "Chelsey Dietrich",
"username": "Kamren",
"email": "Lucio_Hettinger@annie.ca",
"phone": "(254)954-1289",
"website": "demarco.info"
}
]

Step 3: Create a simple table.

Open your component where you need to add the table and paste the below code inside.

import { useTable } from "react-table";
import usersData from "./data/users.json";

const columns = [
{ Header: "ID", accessor: "id" },
{ Header: "Name", accessor: "name" },
{ Header: "Username", accessor: "username" },
{ Header: "Email", accessor: "email" },
{ Header: "Phone", accessor: "phone" },
{ Header: "Website", accessor: "website" },
];

function App() {
const data = useMemo(() => usersData, []);

const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } =
useTable({ columns, data });

return (
<div className="App">
<table {...getTableProps()}>
<thead>
{headerGroups.map((headerGroup) => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map((column) => (
<th {...column.getHeaderProps()}>{column.render("Header")}</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map((row) => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map((cell) => (
<td {...cell.getCellProps()}>{cell.render("Cell")}</td>
))}
</tr>
);
})}
</tbody>
</table>
</div>
);
}

Here, we have first declared the data and columnsarrays to be used to create the React Table component.

Step 4: Create Export Functionality

Now, we'll add the export functionality to the table. We will use the CSVLink component from react-csv to create a link that will allow users to download the table data in CSV format.

import "./App.css";
import { CSVLink } from "react-csv";
import usersData from "./data/users.json";
import { useMemo } from "react";
import { useTable } from "react-table";

// Columns array created for table header
const columns = [
{ Header: "ID", accessor: "id" },
{ Header: "Name", accessor: "name" },
{ Header: "Username", accessor: "username" },
{ Header: "Email", accessor: "email" },
{ Header: "Phone", accessor: "phone" },
{ Header: "Website", accessor: "website" },
];

function App() {
// data declared to be used in table taking data from JSON file
const data = useMemo(() => usersData, []);

// Calling react table hook
const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } =
useTable({ columns, data });

// Contains the column headers and table data in the required format for CSV
const csvData = [
["ID", "Name", "Username", "Email", "Phone", "Website"],
...data.map(({ id, name, username, email, phone, website }) => [
id,
name,
username,
email,
phone,
website,
]),
];
return (
<div className="App">
{/* Export Button Start */}
<CSVLink className="downloadbtn" filename="my-file.csv" data={csvData}>
Export to CSV
</CSVLink>
{/* Export Button End */}
{/* Table Start */}
<table {...getTableProps()}>
<thead>
{headerGroups.map((headerGroup) => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map((column) => (
<th {...column.getHeaderProps()}>{column.render("Header")}</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map((row) => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map((cell) => (
<td {...cell.getCellProps()}>{cell.render("Cell")}</td>
))}
</tr>
);
})}
</tbody>
</table>
{/* Table End */}
</div>
);
}

export default App;

We have created csvData array that contains header and table data required to generate the CSV file. We have then parsed our data inside using the map method. Then we added the CSVLink component above our table to create a button to export the file and passed csvData as a prop into it.

Step 5: Style the Table and Button

Now paste the below CSS inside your stylesheet to style your Table.

.App {
width: 80%;
position: relative;
margin: 0 auto;
}

.downloadbtn {
background: black;
color: white;
text-decoration: none;
padding: 5px 10px;
margin: unset;
position: absolute;
right: 0;
top: -32px;

}

table {
font-family: arial, sans-serif;
border-collapse: collapse;
margin-top: 100px;
width: 100%;

}

td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}

tr:nth-child(even) {
background-color: #dddddd;
}

And that’s it! You should now have an export to CSV button in your React Table component.

For any query, you can get in touch with me via LinkedIn

Below you can find the sample GitHub Repository and demo on codesandbox.

--

--

Manish Mandal
How To React

Full Stack Developer | React JS | Next JS | Node JS | Vue JS | Wordpress. Connect with me https://www.linkedin.com/in/manishmandal21/