4

I can't seem to figure out how to load a local .json file and read the content - so I can dump it into some ´state´.

The code looks like this so far:

import React, { Component } from 'react'
import Files from 'react-files'

class LoadFile extends Component {
  render() {
    return (
      <div className="files">
        <Files
          className="files-dropzone"
          onChange={file => {
            console.log(file)
          }}
          onError={err => console.log(err)}
          accepts={['.json']}
          multiple
          maxFiles={3}
          maxFileSize={10000000}
          minFileSize={0}
          clickable
        >
          Drop files here or click to upload
        </Files>
      </div>
    )
  }
}

export default LoadFile

The logged object does not have any of the data buried inside of it..

[Object]
  0: Object
    id: "files-1"
    extension: "json"
    sizeReadable: "288B"
    preview: Object
      type: "file"

2 Answers 2

7

Like @dkniffin said, what behind react-files is DataTransfer.

You could utilize the FileReader API to get the file content and parse it in JSON format, you could see the result in the console section of CodeSandbox below:

Edit FileReader2

constructor() {
  super();
  this.state = {
    jsonFile: {}
  };

  this.fileReader = new FileReader();

  this.fileReader.onload = (event) => {

    // or do whatever manipulation you want on JSON.parse(event.target.result) here.

    this.setState({ jsonFile: JSON.parse(event.target.result) }, () => {
      console.log(this.state.jsonFile);
    });
  };

}

...

render() {

    return (
       <div className="files">
         <Files

          ...

          onChange={file => {
              // we choose readAsText() to load our file, and onload
              // event we rigister in this.fileReader would be triggered.
              this.fileReader.readAsText(file[0]);
          }}
         >
           Drop files here or click to upload
         </Files>
       </div>
    );
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!! I actually had a try with fileReader, but I see that my semantic was wrong.
0

Unfortunately, I don't have a complete answer for you. However, after digging into the source code of react-files for a bit, I found this line:

let filesAdded = event.dataTransfer ? event.dataTransfer.files : event.target.files

It appears that filesAdded will be a FileList, which is basically just an array of File objects. Unfortunately, I don't see a way to get the content from a File object. Maybe someone else can help out with that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.