Categories
React Answers

How to add export to CSV button in React table with JavaScript?

Spread the love

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

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

How to add export to CSV button in React table with JavaScript?

To add export to CSV button in React table with JavaScript, we use the react-csv package.

To install it, we run

npm i react-csv

Then we use it by writing

import { CSVLink, CSVDownload } from "react-csv";

const csvData = [
  ["firstname", "lastname", "email"],
  ["John", "Doe", "john.doe@xyz.com"],
  ["Jane", "Doe", "jane.doe@xyz.com"],
];

const Comp = () => {
  //...
  return <CSVLink data={csvData}>Download me</CSVLink>;
};

to add the CSVLink component to add a button to let the user export the array data into a csv.

We can also write

import { CSVLink, CSVDownload } from "react-csv";

const csvData = [
  ["firstname", "lastname", "email"],
  ["John", "Doe", "john.doe@xyz.com"],
  ["Jane", "Doe", "jane.doe@xyz.com"],
];

const Comp = () => {
  //...
  return <CSVDownload data={csvData} target="_blank" />;
};

to do the same think by adding a link instead of a button.

Conclusion

To add export to CSV button in React table with JavaScript, we use the react-csv package.

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 *