Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read text file in react

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>` 
like image 212
Salvadore Rina Avatar asked Apr 24 '19 12:04

Salvadore Rina


People also ask

How do I view a text file in React?

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.

How do I get text from text in React?

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.


2 Answers

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; 
like image 163
林冠宇 Avatar answered Sep 20 '22 09:09

林冠宇


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);   }); 
like image 38
jmtorralvo Avatar answered Sep 20 '22 09:09

jmtorralvo