Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reactJS and reading a text file

I have a reactJS application where I need to read in a large text file and use the data from the file to populate some arrays. I came across some code examples and I am trying to implement this code:

        readTextFile = file => {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = () => {
            if (rawFile.readyState === 4) {
                if (rawFile.status === 200 || rawFile.status == 0) {
                    var allText = rawFile.responseText;
                    console.log("allText: ", allText);
                    this.setState({
                        fundData: allText
                    });
                }
            }
        };
        rawFile.send(null);
    };

The code is called by executing this line of code:

this.readTextFile("../text/fund_list.txt");

When I execute the application, I get the following error message:

GET http://localhost:8080/text/fund_list.txt 404 (Not Found)

This is what my application structure looks like: enter image description here

The readTextFile function is in the account_balanc.js code and I am trying to read in the text file /text/fund_list.txt. The file does exist so obviously I am not referencing the file correctly but I don't know why.

I have tried this.readTextFile("../text/fund_list.txt") and this.readTextFile("./text/fund_list.txt"); but neither worked. I even tried moving fund_list.txt into the /screens folder and changing the function call to this.readTextFile("fund_list.txt"); but I still get the 404 error message.

Any ideas why?

Thank you.

like image 576
Jonathan Small Avatar asked Sep 17 '18 18:09

Jonathan Small


People also ask

How do I read a text file in react JS?

To read a text file in React, we can use the FileReader constructor. to define the showFile function that gets the selected file from e. target.


Video Answer


3 Answers

I moved the fund_list.txt file into the public/text folder (after I created it) and changed the calling of the function to this.readTextFile("./text/fund_list.txt");

I saw this as a posted solution but then the post was removed (I don't know why) so I can't thank the user who posted it. But this solved my problem.

like image 98
Jonathan Small Avatar answered Sep 29 '22 11:09

Jonathan Small


You can use webpack raw loader and directly import the .txt file into the component.

First, install raw-loader:

npm i -D raw-loader

Second, add the loader to your webpack config:

// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.txt$/,
        use: 'raw-loader'
      }
    ]
  }
}

Then, directly import .txt to your component:

import txt from './file.txt';
like image 44
Soroush Chehresa Avatar answered Sep 29 '22 12:09

Soroush Chehresa


Using HTML5 FileReader API you can easily read any file. Please have look at the following code:

function App() {
  const [json, setJson] = useState("");
  let fileInputRef = React.createRef();

  return (
    <div className="App">
      <p>{json}</p>
      <input
        type="file"
        ref={fileInputRef}
        style={{ display: "none" }}
        onChange={async e => {
          const reader = new FileReader();
          reader.onload = function() {
            const text = reader.result;
            setJson(text);
          };
          reader.readAsText(e.target.files[0]);
        }}
        accept=".json,application/json"
      />
      <button
        onClick={() => {
          fileInputRef.current.click();
        }}
      >
        Upload JSON file
      </button>
    </div>
  );
}

Here is a working Demo

like image 36
ziishaned Avatar answered Sep 29 '22 12:09

ziishaned