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:
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.
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.
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.
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';
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With