DEV Community

Donna Brown
Donna Brown

Posted on

3 1

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
moutafatin1 profile image
moutafatin1

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

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️