How to import a .txt file from my source?
Not wanting to use fetch as it makes me have to deal with async responses. I solved my problem like this.
- Created a seperate .js file and assigned my text to a variable
- Exported the variable
const mytext = `test
this is multiline text.
more text`;
export default mytext ;
- In my other component, I import the file.
import mytext from './mytextfile.js';
- I am now free to assign it to a variable or use it anywhere in my component.
const gotTheText = mytext;
return (<textarea defaultValue={gotTheText}></textarea>);
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"
This works well in practice:
import React from 'react';
import textfile from "../assets/NOTES.txt";
function Notes() {
const [text, setText] = React.useState();
fetch(textfile)
.then((response) => response.text())
.then((textContent) => {
setText(textContent);
});
return text || "Loading...";
}
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