Sunday, September 22, 2024
Google search engine
HomeLanguagesHow to Read CSV files in React.js ?

How to Read CSV files in React.js ?

React is a popular Javascript library created by Facebook for building user interfaces. It provides a powerful way of DOM manipulation by introducing the concept of virtual DOM. It is mainly used to build single-page applications.

Some of the key features of React.js are:

  • Performance
  • One-way data flow
  • Component-based

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. One popular library that simplifies this process is Papa Parse. In this article, we will learn to read CSV files and convert them to JSON format using a package called Papa Parse.

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

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: Once you have your project setup, run the following command to install the papa parse package.

 npm install papaparse

Project structure: 

 

For the scope of this project, we will only focus on src/App.js file. We’ll start by cleaning up the boilerplate code for simplicity. For this example, we will first create an input component to input the CSV file from the user, then we check if the file’s format is CSV or not, if it’s not CSV we’ll show an error state. Once the user has uploaded the CSV file we’ll parse it using the papa parser and show all the column names in our browser.

Explanation: Firstly we initialized all the states, the data state will contain the parsed JSON data, the error state will show the error if the user tries to enter a file with a different extension and the file state will contain the CSV file uploaded by the user. Then we define a function called handleFileChange which sets the file state after checking the extension. The handleParse function will parse the CSV data using the papa parser and set the data state to the columns of the CSV file. Then we finally return the component which contains an input element to take the uploaded file, a button to parse the data on click, and a container to show any errors or parsed data.

Javascript




import React, { useState } from "react";
import Papa from "papaparse";
 
// 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 setError("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 columns = Object.keys(parsedData[0]);
            setData(columns);
        };
        reader.readAsText(file);
    };
 
    return (
        <div>
            <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((col,
                    idx) => <div key={idx}>{col}</div>)}
            </div>
        </div>
    );
};
 
export default App;


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

npm start

Output: 

 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments