DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Donna Brown
Donna Brown

Posted on

How to read a CSV file using React functional components

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([]);
}
Enter fullscreen mode Exit fullscreen mode

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);
  };
Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
moutafatin1 profile image
moutafatin1

Thanks for sharing, maybe add highlights to the code blocks?

Find what you were looking for? Sign up so you can:

Β 
🌚 Enable dark mode
πŸ”  Change your default font
πŸ“š Adjust your experience level to see more relevant content