I try to import a .txt file to show the text in a text box.
My code:
import React, { Component } from \'react\';
import \'./LoadMyFile.css\';
import
You should use a json file instead:
sample.json
:
{
"text": "some sample text"
}
component:
import { text } from './sample.json';
console.log(text); // "some sample text"
Not wanting to use fetch as it makes me have to deal with async responses. I solved my problem like this.
const mytext = `test
this is multiline text.
more text`;
export default mytext ;
import mytext from './mytextfile.js';
const gotTheText = mytext;
return (<textarea defaultValue={gotTheText}></textarea>);
I converted the text to base64 and then decoded it.
const base64textfile ="Asdfsdfsf";
export default base64textfile ;
import { base64decode } from "nodejs-base64";
var decodedText = base64decode(base64textfile);
I've solved my problem.
handleClick = () => {
fetch('/sample.txt')
.then((r) => r.text())
.then(text => {
console.log(text);
})
}
Tis link did help: Fetch local JSON file from public folder ReactJS