Open In App

How to Read CSV files in React.js ?

Improve
Improve
Like Article
Like
Save
Share
Report

CSV (Comma-Separated Values) files are a common format for storing and exchanging tabular data. When working with React.js, reading and parsing CSV files can be a useful task for handling data input. To read CSV files in React JS we have to use external libraries as there in no inbuilt methods available for it.

Approach

To Read CSV in react and present the data on the webpage we will be using a library named Papa Parse. It is a powerful and fast Javascript in-browser CSV parser. It provides a simple syntax for parsing CSV files and reading them in JSON format.

Some of the key features of papa parse are: 

  • Stream large files
  • Easy to use
  • Type support 
  • Correctly handles line breaks and quotations
  • Works without any other dependencies 
  • Auto-detect delimiter

Steps to Create React Application

Step 1: Let’s create a new React project to see papa parse in action. Run the following command to create a new react project.

npx create-react-app myproject

Step 2: Switch to the Project Directory

cd myproject

Step 3: Once you have your project setup, run the following command to install the papa parse package.

 npm i papaparse

Project structure

Dependenncies list in Package.json

{
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"papaparse": "^5.4.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router": "^6.17.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
}

Example: Take file input from the user and validate it and pasre usign papa parser library. Update the states to form the array and display the data using array.map.

Javascript




// Filename - App.js
 
import React, { useState } from "react";
import Papa from "papaparse";
import "./App.css";
 
// Allowed extensions for input file
const allowedExtensions = ["csv"];
 
const App = () => {
 
    // This state will store the parsed data
    const [data, setData] = useState([]);
 
    // It state will contain the error when
    // correct file extension is not used
    const [error, setError] = useState("");
 
    // It will store the file uploaded by the user
    const [file, setFile] = useState("");
 
    // This function will be called when
    // the file input changes
    const handleFileChange = (e) => {
        setError("");
 
        // Check if user has entered the file
        if (e.target.files.length) {
            const inputFile = e.target.files[0];
 
            // Check the file extensions, if it not
            // included in the allowed extensions
            // we show the error
            const fileExtension =
                inputFile?.type.split("/")[1];
            if (
                !allowedExtensions.includes(fileExtension)
            ) {
                setError("Please input a csv file");
                return;
            }
 
            // If input type is correct set the state
            setFile(inputFile);
        }
    };
    const handleParse = () => {
     
        // If user clicks the parse button without
        // a file we show a error
        if (!file) return alert("Enter a valid file");
 
        // Initialize a reader which allows user
        // to read any file or blob.
        const reader = new FileReader();
 
        // Event listener on reader when the file
        // loads, we parse it and set the data.
        reader.onload = async ({ target }) => {
            const csv = Papa.parse(target.result, {
                header: true,
            });
            const parsedData = csv?.data;
            const rows = Object.keys(parsedData[0]);
 
            const columns = Object.values(parsedData[0]);
            const res = rows.reduce((acc, e, i) => {
                return [...acc, [[e], columns[i]]];
            }, []);
            console.log(res);
            setData(res);
        };
        reader.readAsText(file);
    };
 
    return (
        <div className="App">
            <h1 className="geeks">GeeksforGeeks</h1>
            <h3>Read CSV file in React</h3>
            <div className="container">
                <label
                    htmlFor="csvInput"
                    style={{ display: "block" }}
                >
                    Enter CSV File
                </label>
                <input
                    onChange={handleFileChange}
                    id="csvInput"
                    name="file"
                    type="File"
                />
                <div>
                    <button onClick={handleParse}>
                        Parse
                    </button>
                </div>
                <div style={{ marginTop: "3rem" }}>
                    {error
                        ? error
                        : data.map((e, i) => (
                              <div key={i} className="item">
                                  {e[0]}:{e[1]}
                              </div>
                          ))}
                </div>
            </div>
        </div>
    );
};
 
export default App;


CSS




/* Filename - App.css */
 
.App {
    text-align: center;
}
 
.geeks {
    color: green;
}
 
 
.container {
    display: flex;
    flex-direction: column;
    width: 35rem;
    margin: 2% auto;
    box-shadow: 0px 5px 10px gray;
    border-radius: 15px;
    padding: 3%;
}
 
.item {
    width: 200px;
    margin: 0 auto;
    padding: 2px;
    border-radius: 10px;
    text-align: left;
}
 
label {
    width: 150px;
    border-radius: 5px;
    background-color: green;
    color: white;
    font-size: larger;
    margin: auto;
    padding: 3px;
}
 
#csvInput {
    display: none;
}


Step to run the application: Open the terminal and type the following command.

npm start

Output: This output will be visible on http://localhost:3000/ on browser window.

Peek-2023-10-19-11-06



Last Updated : 25 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads