45

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>
fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88
Salvadore Rina
  • 559
  • 1
  • 4
  • 7
  • what you mean by 'htm sample code'? have you tried `./data.txt`? – ProblemsEverywhere Apr 24 '19 at 12:48
  • @Drusto i have and same results, This is a bit of the output: " – Salvadore Rina Apr 24 '19 at 12:59
  • The first answer can be accepted, but that is something that will not work unless you will add loader for webpack configurations, which will allow you to import text file. You can check [raw-loader](https://github.com/webpack-contrib/raw-loader) (A loader for webpack that allows importing files as a String.) – Hayk Aghabekyan Apr 24 '19 at 12:55

4 Answers4

63

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;
Kuan-Yu Lin
  • 934
  • 7
  • 9
  • 8
    Came here looking for THIS answer, as loading a file from the app itself wasn't the issue that led me here. – Taersious Apr 11 '21 at 23:26
41

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);
});
fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88
jmtorralvo
  • 511
  • 4
  • 3
18

Try below approach :

import text from './data.js'; // The relative path to your File

console.log(text); 

Create a file called data.js and add below content :

const text = "My Text goes here";

export default text;
Tetie
  • 365
  • 1
  • 14
KOTIOS
  • 11,177
  • 3
  • 39
  • 66
0

As React is JavaScript, so this code should work.

Html

<input type="file" id="fileInput" onchange="onLoad(event)">

JavaScript

onLoad = function (event){
 var file = fileInput.files[0];
    var textType = /text.*/;
    
    if (file.type.match(textType)) {
        var reader = new FileReader();
        
        reader.onload = function(e) {
            var content = reader.result;
            // Here the content has been read successfuly
            alert(content);
        }
        
        reader.readAsText(file);    
    } 
}

Event this will work, if directly on page load if you want to load the data.

import { text } from './data.txt'; // Relative path to your File
console.log(text); 
fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88