Write CSV file in React: CSV (Comma Separated Value) files are commonly used to store and share data. In a React application, there may be a need to create and write to CSV files. In this blog post, we will discuss how to write CSV files using React.
Understanding CSV Format
Before we start, it’s important to understand the CSV format. A CSV file is a text file that contains data separated by commas. Each line in the file represents a row, and each value is separated by a comma. For example, the following CSV file contains three rows and three columns:
Name, Age, Gender
John, 28, Male
Jane, 30, Female
Installing the Required Libraries
We will be using two libraries to write CSV files in React – papaparse and file-saver. Papaparse is a powerful CSV parsing and writing library, and file-saver allows us to save files from the browser.
Also read: How do I make an HTTP request in Javascript?
You can install both libraries using npm:
npm install papaparse file-saver
Creating the CSV Data
Now that we have installed the required libraries, we can start creating the CSV data. In this example, we will create an array of objects, where each object represents a row in the CSV file. We will then use papaparse to convert this array into a CSV string.
import Papa from 'papaparse';
const data = [
{ name: 'John', age: 28, gender: 'Male' },
{ name: 'Jane', age: 30, gender: 'Female' }
];
const csv = Papa.unparse(data);
Writing the CSV File
We now have the CSV data in a string format, and we can use file-saver to save it as a file. In this example, we will create a button that, when clicked, will download the CSV file.
import { saveAs } from 'file-saver';
function handleDownload() {
const data = [
{ name: 'John', age: 28, gender: 'Male' },
{ name: 'Jane', age: 30, gender: 'Female' }
];
const csv = Papa.unparse(data);
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
saveAs(blob, 'data.csv');
}
function App() {
return (
<div>
<button onClick={handleDownload}>Download CSV</button>
</div>
);
}
export default App;
In the above code, we create a Blob object from the CSV data, set the MIME type to “text/csv”, and then use file-saver’s saveAs function to save the file.
Conclusion
In this blog post, we discussed how to write CSV files using React. We used papaparse to convert an array of objects into a CSV string and file-saver to save the file from the browser. This technique can be used to create and save CSV files from any React application.