zeeshan sarwar
zeeshan sarwar

Reputation: 71

How to read file in React js?

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'

Upvotes: 5

Views: 17477

Answers (3)

abdul
abdul

Reputation: 360

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

Upvotes: 1

zeeshan sarwar
zeeshan sarwar

Reputation: 71

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;

Upvotes: 1

Alexandre Rodrigues
Alexandre Rodrigues

Reputation: 730

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;

Upvotes: 1

Related Questions