React 18 Bootstrap Import CSV File Data to Bootstrap Table Tutorial

Last Updated on by in React JS

This comprehensive tutorial will teach you how to import CSV file data to a React table using the Bootstrap CSS library.

CSV stands for “Comma-Separated Values”. It is a file format used for storing tabular data in plain text.

In a CSV file, each line represents a row of data, and each value within a row is separated by a comma.

CSV files are commonly used to exchange data between different software applications, as they are easy to read and parse.

Bootstrap is a popular front-end development framework that allows developers to create responsive, mobile-first web designs quickly and easily.

It offers a set of pre-designed HTML, CSS, and JavaScript components that can be used to create responsive layouts, forms, buttons, navigation menus, and other user interface elements.

How to Create and Customize Range Slider in React JS using React Material UI

  • Step 1: Install React Framework
  • Step 2: Install Bootstrap Library
  • Step 3: Create New Function Class
  • Step 4: Implement Import CSV to Table
  • Step 9: Register Component in App
  • Step 10: Run Development Server

Install React Framework

First, you have to create a new React project using create-react-app or any other method you like.

npx create-react-app react-demo
cd react-demo

Install Bootstrap Library

Next, we have to install the required dependency, we will add Bootstrap in React by running the following command in your terminal:

npm install bootstrap --legacy-peer-deps

Further, you will be adding given CSS modules in the App.css file.

@import url("https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap");
@import "@fontsource/roboto/300.css";
@import "@fontsource/roboto/400.css";
@import "@fontsource/roboto/500.css";
@import "@fontsource/roboto/700.css";

Create New Function Class

Inside the src/ folder, you will have to create the features/ folder, and then define the CsvTable component by adding the given code into the CsvTable.js file.

import React from 'react'

function CsvTable() {
  return (
    <div></div>
  )
}

export default CsvTable

Implement Import CSV to Table

To read the data from the CSV and displaying on the table, the following code must be placed within the features/CsvTable.js file.

import React, { useState } from "react";
import axios from "axios";
import { useQuery } from "@tanstack/react-query";

function CsvTable() {
  const [file, setCSVFile] = useState();
  const [array, setArray] = useState([]);

  const fileReader = new FileReader();

  const handleOnChange = (e) => {
    setCSVFile(e.target.files[0]);
  };

  const csvArray = (string) => {
    const header = string.slice(0, string.indexOf("\n")).split(",");
    const rows = string.slice(string.indexOf("\n") + 1).split("\n");

    const array = rows.map((i) => {
      const values = i.split(",");
      const obj = header.reduce((object, header, index) => {
        object[header] = values[index];
        return object;
      }, {});
      return obj;
    });

    setArray(array);
  };

  const onFileSubmit = (e) => {
    e.preventDefault();

    if (file) {
      fileReader.onload = function (event) {
        const text = event.target.result;
        csvArray(text);
      };

      fileReader.readAsText(file);
    }
  };

  const headerVal = Object.keys(Object.assign({}, ...array));

  return (
    <>
      <div className="mb-3">
        <form>
          <input
            type={"file"}
            id={"csvFileInput"}
            accept={".csv"}
            onChange={handleOnChange}
            className="form-control mb-3"
          />

          <button
            onClick={(e) => {
              onFileSubmit(e);
            }}
            className="btn btn-danger mb-3"
          >
            Import CSV
          </button>
        </form>
        

        <table className="table table-dark table-striped">
          <thead className="table-primary">
            <tr key={"header"}>
              {headerVal.map((key) => (
                <th key={key}>{key}</th>
              ))}
            </tr>
          </thead>

          <tbody>
            {array.map((item) => (
              <tr key={item.id}>
                {Object.values(item).map((val) => (
                  <td>{val}</td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

export default CsvTable;

Register Component in App

In this section, we will update the App.js file; this allows us to inject the CsvTable component in the React environment.

import React from "react";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import CsvTable from "./features/CsvTable";

function App() {
  return (
    <div className="container mt-3">
      <h2 className="mb-3">React Import CSV Data in Bootstrap Table Example</h2>
      <CsvTable />
    </div>
  );
}

export default App;

Run Development Server

Start the development server by running the following command:

npm start

Above command will start the app and open it directly on your default web browser at:

http://localhost:3000

React Bootstrap Import CSV File Data to Bootstrap Table Tutorial

Conclusion

In this detailed guide, we have learned how to import CSV data in an HTML table in React application using the Bootstrap package.

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.