Categories
React Answers

How to add export to CSV button in a React table?

Spread the love

Sometimes, we want to add export to CSV button in a React table.

In this article, we’ll look at how to add export to CSV button in a React table.

How to add export to CSV button in a React table?

To add export to CSV button in a React table, we can use the react-csv library.

To install it, we run:

npm i react-csv

Then we add the button to the table by writing:

import React from "react";
import { useTable } from "react-table";
import { CSVLink } from "react-csv";

const csvData = [
  { firstName: "John", lastName: "Doe" },
  { firstName: "Jane", lastName: "Doe" }
];

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

  return (
    <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, i) => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map((cell) => {
                return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
};

export default function App() {
  const columns = React.useMemo(
    () => [
      {
        Header: "Name",
        columns: [
          {
            Header: "First Name",
            accessor: "firstName"
          },
          {
            Header: "Last Name",
            accessor: "lastName"
          }
        ]
      }
    ],
    []
  );

  const data = React.useMemo(() => {
    return csvData.map((d) => Object.values(d));
  }, []);

  return (
    <>
      <CSVLink data={data}>Download me</CSVLink>
      <Table columns={columns} data={csvData} />;
    </>
  );
}

We create the Table component which calls the useTable hook with the columns and data props to return an object that has the properties we use to create the table.

Next, we add a CSV download link by using the CSVLink component.

We pass in a nested array as the value of the data prop so react-csv can generate the CSV from it.

We create the nested array by calling useMemo with a callback that returns the nested array which we create by calling csvData.map with a callback that returns the values in an array from each csvData entry with Object.values.

Now we should see a Download me button which we can click to download the CSV.

Conclusion

To add export to CSV button in a React table, we can use the react-csv library.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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