5

i want to read csv file in reactJS. i am trying file system ('fs') but it is not working.

Below is my same working code in nodejs,but it i not working in ReactJs. can somebody guide me how to read file in React js. Do we have any simple method for this ? i just want to read file from same project directory.

Working code in node js

const CSVToJSON = require("csvtojson");
const CSVToCSV = require("jsontocsv");
const FileSystem = require("fs");

CSVToJSON().fromFile("./ca-500.csv").then(source => {
    console.log(source);
})

But when tried in React js it is giving below mentioned error

Error: Cannot find module 'fs'

1
  • By either bundling it in using a csv loader (e.g. you webpack it into your bundle), or by being nice to your users and network-fetching it only when you actually need it, using the Fetch API. If it's static CSV data, just convert it to a normal JS file and load that instead using a plain require/import. Takes seconds in any modern code editor. Don't use entire libraries for on-the-fly conversion work that you can do yourself up front so you never even need to convert any data. Commented Mar 26, 2022 at 1:05

3 Answers 3

1

you can try react-csv-reader

npm install --save react-csv-reader

example

Usage

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import CSVReader from 'react-csv-reader'

class App extends Component {
  ...

  render() {
    return (
      <CSVReader
        cssClass="csv-reader-input"
        label="Select CSV with secret Death Star statistics"
        onFileLoaded={this.handleForce}
        onError={this.handleDarkSideForce}
        inputId="ObiWan"
        inputStyle={{color: 'red'}}
      />
    )
  }
}

ReactDOM.render(<App />, document.getElementById('root'))

Alternatively you can use React File Reader

npm install react-file-reader --save

<ReactFileReader handleFiles={this.handleFiles} fileTypes={'.csv'}>
    <button className='btn'>Upload</button>
</ReactFileReader>
handleFiles = files => {
    var reader = new FileReader();
    reader.onload = function(e) {
    // Use reader.result
    alert(reader.result)
    }
  reader.readAsText(files[0]);
}

example

If you just want read a local file you can use papaparse

npm install papaparse

import React from 'react';
import Papa from 'papaparse';

class DataController extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            data: []
        };

        this.getData = this.getData.bind(this);
    }

    componentWillMount() {
        this.getCsvData();
    }

    fetchCsv() {
        return fetch('./ca-500.csv').then(function (response) {
            let reader = response.body.getReader();
            let decoder = new TextDecoder('utf-8');

            return reader.read().then(function (result) {
                return decoder.decode(result.value);
            });
        });
    }

    getData(result) {
        this.setState({data: result.data});
    }

    async getCsvData() {
        let csvData = await this.fetchCsv();

        Papa.parse(csvData, {
            complete: this.getData
        });
    }

    render() {
        return (
            <section className="data-controller">
                ...
            </section>
        );
    }
}

export default DataController;
Sign up to request clarification or add additional context in comments.

1 Comment

its working but it is not showing the actual data on browser console, instead it is showing some html , " "<!DOCTYPE html>" ] ​ 1: Array [ "<html lang=\"en\">" ] ​ 2: Array [ " <head>" ] ​ 3: Array [ " <meta charset=\"utf-8\" />" ] ​ 4: Array [ " <link rel=\"shortcut icon\" href=\"/favicon.ico\" />" ] ​ 5: Array [ " <meta name=\"viewport\" content=\"width=device-width", " initial-scale=1\" />" ] ​ 6: Array [ " <meta name=\"theme-color\" content=\"#000000\" />" ] ​ 7: Array [ DataController.js:46 " like this
1

i have found the correct solution. it was answered below some other question. Here is the link to that question.

How should I parse this json object in react with lifecycle method?

and the correct working code

import React, {Component} from 'react';

import './App.css';

import * as d3 from 'd3';

import data from './data_set/data.csv';

class App extends Component {

constructor(props) {
    super(props)
}

componentDidMount() {

    d3.csv(data).then(function(data) {
        console.log(data)
    }).catch(function(err) {
        throw err;
    })
}

render() {


    return ( 
             <div className = "App" >
              <div> Data Visualization </div> 
             </div>
        );
    }
}

export default App;

Comments

1

You can use FileReader onload methods to read the file data

You can find this useful to handle files using File Reader in React ReactJS File Reader

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.