Parsing CSV files in ReactJs
This article discusses how to read and parse a “.CSV” file in a React component. This is very helpful in building components like bulk upload details in react.
Install the required packages:
To install the package, type one of the following commands based on your package manager
For npm:
npm install csv
For yarn:
yarn add csv
Parsing the CSV file using the “CSV” package:
- We have to upload a CSV file using input before parsing it. Let us create an HTML input for uploading the file. A simple HTML input is defined in the below code.
The uploaded file will be under event.target.files. We are only using the first array item from files as we uploaded only one file.
- Now we just had to add the csv module to the React component using
import csv from ‘csv’;
. Then, we have to use the csv package to parse the uploaded file. - Now add the following code to the
onFileUpload
function to parse the uploaded file.
const onFileUpload = (event) => { const fileReader = new FileReader(); fileReader.onload = () => { csv.parse(fileReader.result, (err, data) => { const [header, ...csv_data] = data; console.log(header, csv_data); }); }; fileReader.readAsBinaryString(event.target.files[0]);};
The headers will come as a first array item in data, then the CSV data will be followed.
The full example of how this code can be used in an upload component using ReactJs.
Be Amazed!
Hooray! We have successfully parsed a CSV file in ReactJs.
Say Hi, It’s free at @matheswaaran_S or https://matheswaaran.com