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?
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.
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
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>);
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