Here is code to read in a .csv file using React hooks and functional components. CsvReader is a functional component which uses the useState hook to save the filename and data read in from the file to state variables. This is GitHub link: https://github.com/donnabrown77/csv-reader.
I included a child component to display the CSV data in an HTML table. Here is a link to this code:
https://dev.to/dbrownsoftware/how-to-create-a-reusable-html-table-in-react-30pf.
First create a functional component and state variables.
const CsvReader = () => { // save the input file name to a state variable const [csvFile, setCsvFile] = useState(null); // save the file data to a state variable // so the DisplayTable component can use it const [csvArray, setCsvArray] = useState([]); }
Each line of csv data is separated by a newline character. So that needs to be removed. Use the map function to replace commas with a space. Then call setCsvArray with the row data.
Next, write a function to handle the file upload.
const handleFileUpload = () => { const file = csvFile; const reader = new FileReader(); reader.onload = function (e) { const text = e.target.result; processCSV(text); }; reader.readAsText(file); };
Setup the functional component. Return jsx with input type="file" and accept=".csv" and a button with an onClick event handler. DisplayTable is a child component I wrote to display html table without hard coding the table header, row, and cell data. It is optional.
return ( <div> <input type="file" accept=".csv" onChange={(e) => { setCsvFile(e.target.files[0]); }} /> <button onClick={(e) => { e.preventDefault(); handleFileUpload(); }} > Submit </button> <br /> <DisplayTable value={csvArray} /> </div> ); }; export default CsvReader;
This is the final result:
import React from "react"; import { useState } from "react"; import DisplayTable from "./DisplayTable"; const CsvReader = () => { // save the input file name to a state variable const [csvFile, setCsvFile] = useState(null); // save the file data to a state variable // so the DisplayTable component can use it const [csvArray, setCsvArray] = useState([]); const processCSV = (str) => { // split the file data into rows from the newline character let rows = str.split("\n"); // remove comma rows = rows.map(function (row) { return row.replace(/,/g, " "); }); setCsvArray(rows); }; const handleFileUpload = () => { const file = csvFile; const reader = new FileReader(); reader.onload = function (e) { const text = e.target.result; processCSV(text); }; reader.readAsText(file); }; return ( <div> <input type="file" accept=".csv" onChange={(e) => { setCsvFile(e.target.files[0]); }} /> <button onClick={(e) => { e.preventDefault(); handleFileUpload(); }} > Submit </button> <br /> <DisplayTable value={csvArray} /> </div> ); }; export default CsvReader;
Top comments (1)
Thanks for sharing, maybe add highlights to the code blocks?