50

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>
3
  • what you mean by 'htm sample code'? have you tried ./data.txt? Commented Apr 24, 2019 at 12:48
  • 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 (A loader for webpack that allows importing files as a String.) Commented Apr 24, 2019 at 12:55
  • @Drusto i have and same results, This is a bit of the output: "<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="shortcut ico" Commented Apr 24, 2019 at 12:59

4 Answers 4

72

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Came here looking for THIS answer, as loading a file from the app itself wasn't the issue that led me here.
51

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);
});

3 Comments

Thanks! This solved my problem of trying to load a YAML file. fs didn't work, so I'm glad that fetch did!
Got "Cannot find module '../foo1/foo2.txt' or its corresponding type declarations."
@Benur21 you can add the following code in Declaration File(d.ts) declare module '*.txt';
17

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;

9 Comments

Please post screenshot of you code and the code structure
I cannot see above code in screenshot 1, you still using old approach
i am not following you
import { text } from './data.txt'; this line is in your code?
changing "import { text } from './data.js'"; to "import text from './data.js';" made it work for me
|
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.