Home » How To Display CSV Data in a Table in React JS

How To Display CSV Data in a Table in React JS

how to display csv file data in table react js

In this blog post, we will learn how to display CSV data in a table using React js. We will go through the step-by-step process of implementing this functionality in a React application. Let’s dive into the code!

As you can see in the above demo video, we are using the file input element to get the CSV file. And we are parsing the CSV data and displaying it in a table.

How to Display CSV Data in a Table in React JS

Step 1: Handling CSV File Selection

The first step is to handle the file selection by the user. We need to define a state variable to hold the CSV data and a function to update that state variable.

const [csvData, setCsvData] = useState([]);

The csvData state variable will be used to store the parsed CSV data. Now, let’s define the handleFileChange function to handle the file selection event.

const handleFileChange = (event) => {
  const file = event.target.files[0];

  if (file) {
    const reader = new FileReader();

    reader.onload = (e) => {
      const csvText = e.target.result;
      parseCSV(csvText);
    };

    reader.readAsText(file);
  }
};

The handleFileChange function accepts an event parameter, which represents the file selection event. It retrieves the selected file using event.target.files[0] and checks if a file is selected. If a file exists, it creates a FileReader object to read the file contents.

When the file is loaded, the onload event is triggered, and we can access the CSV data using e.target.result. We then pass the CSV text to the parseCSV function.

Step 2: Parsing CSV Data

The next step is to parse the CSV data and convert it into a format that can be easily displayed in a table. Add the following code to the App component.

const parseCSV = (csvText) => {
  const lines = csvText.split("\n");
  const headers = lines[0].split(",");
  const parsedData = [];

  for (let i = 1; i < lines.length; i++) {
    const currentLine = lines[i].split(",");

    if (currentLine.length === headers.length) {
      const row = {};
      for (let j = 0; j < headers.length; j++) {
        row[headers[j].trim()] = currentLine[j].trim();
      }
      parsedData.push(row);
    }
  }

  setCsvData(parsedData);
};

The parseCSV function accepts the CSV text as a parameter. It first splits the text into individual lines using csvText.split("\n"). The first line contains the headers, so we split it by commas to get an array of headers. We initialize an empty array called parsedData to store the parsed rows.

Next, we iterate over the remaining lines, starting from index 1. For each line, we split it by commas to get the individual values. We check if the number of values matches the number of headers to ensure data integrity. 

If they match, we create an empty object called row and populate it with key-value pairs using the headers and corresponding values. 

Finally, we push the row object into the parsedData array. After parsing is complete, we update the csvData state variable with the parsed data using setCsvData(parsedData).

Step 3: Rendering the Components

Now that we have the file handling and CSV parsing logic in place, let’s render the necessary components and wire up the functionality. Update the return statement of the App component as follows:

return (
  <div>
    <div style={{ marginBottom: "15px" }}>
      <input type="file" onChange={handleFileChange} accept=".csv" />
    </div>
    <CSVDataTable data={csvData} />
  </div>
);

In the above code, we have a container div that holds the file input element. The onChange event is attached to the input element, which triggers the handleFileChange function when a file is selected. We restrict the file selection to only CSV files using the accept attribute.

We also have a custom component called CSVDataTable that we will create in the next step. The CSVDataTable will render the CSV data in a table format and it takes csvData as a prop named data.

App.js Complete code:

import React, { useState } from "react";
import CSVDataTable from "./CSVDataTabel";

const App = () => {
  const [csvData, setCsvData] = useState([]);

  const handleFileChange = (event) => {
    const file = event.target.files[0];

    if (file) {
      const reader = new FileReader();

      reader.onload = (e) => {
        const csvText = e.target.result;
        parseCSV(csvText);
      };

      reader.readAsText(file);
    }
  };

  const parseCSV = (csvText) => {
    const lines = csvText.split("\n");
    const headers = lines[0].split(",");
    const parsedData = [];

    for (let i = 1; i < lines.length; i++) {
      const currentLine = lines[i].split(",");

      if (currentLine.length === headers.length) {
        const row = {};
        for (let j = 0; j < headers.length; j++) {
          row[headers[j].trim()] = currentLine[j].trim();
        }
        parsedData.push(row);
      }
    }

    setCsvData(parsedData);
  };

  return (
    <div>
      <div style={{marginBottom:'15px'}}>
        <input type="file" onChange={handleFileChange} accept=".csv" />
      </div>
      <CSVDataTable data={csvData} />
    </div>
  );
};

export default App;

Step 4: Creating CSVDataTable Component

Let’s start by creating a new file called CSVDataTable.js. Inside the CSVDataTable component, we will render the table based on the provided data.

import React from "react";

const CSVDataTable = ({ data }) => {
  const headers = data.length > 0 ? Object.keys(data[0]) : [];

  return (
    <>
      {data.length === 0 ? (
        <p>No data available.</p>
      ) : (
        <table style={tableStyle}>
          <thead>
            <tr>
              {headers.map((header, index) => (
                <th key={index} style={tableHeaderStyle}>
                  {header}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {data.map((row, index) => (
              <tr key={index}>
                {headers.map((header, columnIndex) => (
                  <td key={columnIndex} style={tableCellStyle}>
                    {row[header]}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </>
  );
};

const tableStyle = {
  borderCollapse: "collapse",
  width: "100%",
  borderRadius: "10px",
  overflow: "hidden",
  boxShadow: "40px 90px 55px -20px rgba(155, 184, 243, 0.2)",
};

const tableHeaderStyle = {
  fontSize: "14px",
  fontWeight: 500,
  color: "#ffffff",
  backgroundColor: "#6D95E0",
  borderBottom: "1px solid #ddd",
  padding: "15px",
  textAlign: "left",
};

const tableCellStyle = {
  fontSize: "14px",
  fontWeight: 500,
  borderBottom: "1px solid #ddd",
  padding: "15px",
  backgroundColor: "#fff",
};

export default CSVDataTable;

Let’s break down the code above:

  • We start by defining a constant called headers, which stores an array of column headers. We extract the headers from the first row of the data array using Object.keys(data[0]). We check if the data is not empty before extracting the headers to avoid any errors.
  • We use conditional rendering to check if the data array is empty. If it is empty, we render a simple message saying “No data available.”
  • If the data array is not empty, we render the table.
  • Inside the thead element, we render a row of table headers. We use the headers.map method to iterate over the headers array and render a th element for each header. We assign a unique key prop to each th element.
  • Inside the tbody element, we iterate over the data array using the data.map method. For each row in the data array, we render a tr element and iterate over the headers array to render the corresponding td elements. We use the row[header] syntax to access the value of each column for the current row. Again, we assign a unique key prop to each td element.

Finally, we define the tableHeaderStyle and tableCellStyle objects, which contain the respective styles for the table headers and cells.

Also, check out:

Output:

display csv data in table react

Conclusion

That’s it! We have successfully implemented the functionality to display CSV data in a table using React.js. The handleFileChange function handles file selection and triggers the CSV parsing logic, which converts the CSV text into an array of objects. The csvData state variable holds the parsed data, which is passed to the CSVDataTable component for rendering.

Feel free to customize the rendering logic in the CSVDataTable component to suit your needs. Happy coding!

Leave a Reply

Your email address will not be published.