Open In App

How to Read CSV files in React.js ?

Last Updated : 09 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
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

Reading CSV files is a common requirement for data-driven applications.

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.

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;
}
JavaScript

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.



Next Article

Similar Reads