Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a .txt file from my source?

Tags:

reactjs

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 myText from './sample.txt';  export default class LoadMyFile extends Component {     render() {     return (       <div>               <button onClick={this.handleClick} className="LoadMyFile" name="button" variant="flat">test string</button>       </div>     )   }     handleClick = () => {     console.log(myText);   }    } 

But i see in console: /static/media/sample.f2e86101.txt

What is going wrong here?

like image 777
Edelfix Avatar asked May 26 '18 05:05

Edelfix


People also ask

How do I load a TXT file in Python?

To read a text file in Python, you follow these steps: First, open a text file for reading by using the open() function. Second, read text from the text file using the file read() , readline() , or readlines() method of the file object. Third, close the file using the file close() method.


2 Answers

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

like image 65
Edelfix Avatar answered Sep 23 '22 17:09

Edelfix


Not wanting to use fetch as it makes me have to deal with async responses. I solved my problem like this.

  1. Created a seperate .js file and assigned my text to a variable
  2. Exported the variable
const mytext = `test  this is multiline text.  more text`;  export default mytext ; 
  1. In my other component, I import the file.
import mytext from './mytextfile.js'; 
  1. 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>); 
like image 37
TBX Avatar answered Sep 21 '22 17:09

TBX