Salvadore Rina
Salvadore Rina

Reputation: 609

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>

Upvotes: 50

Views: 189287

Answers (4)

KOTIOS
KOTIOS

Reputation: 11194

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;

Upvotes: 17

Kusum Kushwaha
Kusum Kushwaha

Reputation: 202

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

Upvotes: 1

jmtorralvo
jmtorralvo

Reputation: 601

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

Upvotes: 50

Kuan-Yu Lin
Kuan-Yu Lin

Reputation: 1034

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;

Upvotes: 72

Related Questions