How to Read CSV files in React.js ?
Last Updated :
09 Jan, 2025
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
// 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;
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.
Similar Reads
How to Convert CSV to JSON in ReactJS ? Dealing with data in various formats is a common task in web development. CSV (Comma Separated Values) and JSON (JavaScript Object Notation) are two widely used formats for storing and transmitting data. Converting CSV to JSON is often required when working with data in ReactJS applications. Approac
4 min read
How to Render Lists in React? In React, rendering lists of data is a common task. There are multiple approaches to achieve this. In this article we will explore various approaches to render lists in React. Table of Content Using map() methodUsing forEach() methodSteps to Setup a React App:Step 1: Create a React application using
2 min read
How to Read and Write Excel file in Node.js ? Read and write excel file in Node is a common task while updating the data from backend. There are many packages available on npm for performing these operations.Approach To read and write Excel file in Node js we will use the xlsx package from NPM. We can read the excel file using readFile method a
4 min read
How to create SpreadSheet in ReactJS ? In this article, we are going to learn how we can create SpreadSheet in ReactJs. A spreadsheet is a file that exists of cells in rows and columns and can help arrange, calculate and sort data.React is a free and open-source front-end JavaScript library for building user interfaces or UI components.
2 min read
How to handle forms in React ? In React, Form handling is one of the basic and important concepts that every developer should learn about. Forms are used to collect the data so that we can use the data for various purposes. This article, lets us understand form handling in React along with examples.Prerequisites:JSXReactuseStateF
6 min read
How To Download PDF file in ReactJS? Downloading files, such as PDFs, in a React application can be easily achieved using two main methods: Using the HTML DOM Anchor Object and using the fetch() Method. Both of these approaches allow you to download files and store them locally, but they differ in flexibility and complexity. Let's expl
4 min read
How to Access Nested Fields in React-Bootstrap-table ? React-Bootstrap-Table provides a set of components and utilities that make it easy to create tables with features like sorting, filtering, pagination, and more. To access nested fields in React-Bootstrap-Table, you can use the dataField property of your column definitions to specify the path to the
2 min read
How to add code input in React JS? In this article, we are going to learn how we can add Code Input in React JS. React is a front-end JavaScript library for constructing user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies. Approach to add code input: To incorporate our
2 min read
How to import recharts.js library to ReactJS file ? Recharts.js is a redefined chart library built with React and D3. It helps in creating interactive line graphs, bar graphs, pie graphs, etc. One of the main principles of it is that all its components are independent, lightweight, and can be deployed easily. Prerequisites:NPM & Node.jsReact JSSt
2 min read
How to create a Read More component in ReactJS? Creating a Read More component in React JS refers to hiding and displaying the text content on the page. It can be achieved by setting the state variable and display the content accordingly. PrerequisitesNode.JS and npmReact JSReact JS useState() hookApproachTo create a Read More component in React
3 min read