Screenshot1 Screenshot2
I want to read from a text file within the react project, but when i try to execute and read i get a HTML sample code in the console log. This is the function:
`onclick= () =>{         fetch('data.txt')             .then(function(response){                 return response.text();             }).then(function (data) {             console.log(data);         })     };`   And the button which calls it:
` <button onClick={this.onclick}>click string</button>` 
                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.
To get the value of a textarea in React, set the onChange prop on the textarea field and access its value as event. target. value or use a ref for an uncontrolled textarea element and access its value as ref.
Simply try the below code and you may understand
import React, { Component } from 'react';  class App extends Component {    constructor(props) {     super(props);   }    showFile = async (e) => {     e.preventDefault()     const reader = new FileReader()     reader.onload = async (e) => {        const text = (e.target.result)       console.log(text)       alert(text)     };     reader.readAsText(e.target.files[0])   }    render = () => {      return (<div>       <input type="file" onChange={(e) => this.showFile(e)} />     </div>     )   } }  export default App; 
                        If you want to get a .txt file first you have to import it:
   import raw from '../constants/foo.txt';  After that, you could fetch it and transform into text:
fetch(raw)   .then(r => r.text())   .then(text => {     console.log('text decoded:', text);   }); 
                        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