How to read text file in react

Salvadore Rina picture Salvadore Rina · Apr 24, 2019 · Viewed 36.5k times · Source

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>`

Answer

林冠宇 picture 林冠宇 · May 30, 2019

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;