woody
woody

Reputation: 45

render json on the client in react

I've created file uploading component in react which is going to upload csv file and parse it and render it as json on the client. But now my code can upload csv file on the console log only, and I have a hard time why it didn't parse csv and render it on the browser (client side).

I looked into react tutorial video but still can't figure out how can I parse and render csv as json output on the client. how can I make this happen? any hack to get this done? any thoughts? Thanks

my file component:

import React, { Component } from 'react'
// import { connect } from 'react-redux'
import ReactFileReader from 'react-file-reader';

export default class FileUpload extends Component {
//   constructor(props) {
//     super(props);
//   }
  // how to post those to database
  constructor(props) {
    super(props)
    this.state = {
      fileUpload_status: 'false'
    }
  };
  handleFiles = files => {
    var reader = new FileReader();
    reader.onload = function(e) {
    // Use reader.result
    var csv = reader.result;
    var lines = csv.split("\n");
    var result = [];
    var headers=lines[0].split(",");
    for(var i=1;i<lines.length;i++){
      var obj = {};
      var currentline=lines[i].split(",");
      for(var j=0;j<headers.length;j++){
        obj[headers[j]] = currentline[j];
      }
      result.push(obj);
      }  
      result= JSON.stringify(result, null, 4); //JSON
    console.log(result);
  }
  reader.readAsText(files[0]);
  // format json as standard json object
}
  render() {
    return (
      <ReactFileReader handleFiles={this.handleFiles} fileTypes={'.csv'}>
        <button className='btn'>Upload</button>
        <div>{console.log(this.props)}</div>
      </ReactFileReader>
    );
  }
}

I got this issue because whenever csv file is uploaded, I want to populate this data to cloud database. I couldn't solve this problem. Can react community helps me out with my issue? is there any hack to fix the issue? any solution?

goal:

I am expecting local csv file to be parsed as json and render the content on the browser (client). how can I achieve my goal? any solution to get this done? thanks

Upvotes: 1

Views: 370

Answers (1)

Junius L
Junius L

Reputation: 16122

Use pre and JSON.stringify()

 this.setState({
    data: JSON.stringify(result, null, 4),
  });

Render your JSON string

 <pre>{this.state.data}</pre>

demo

Upvotes: 4

Related Questions