47

I try to import a .txt file to show the text in a text box.

My code:

import React, { Component } from 'react';
import './LoadMyFile.css';
import myText from './sample.txt';

export default class LoadMyFile extends Component {  
  render() {
    return (
      <div>      
        <button onClick={this.handleClick} className="LoadMyFile" name="button" variant="flat">test string</button>
      </div>
    )
  }  
  handleClick = () => {
    console.log(myText);
  }   
}

But i see in console: /static/media/sample.f2e86101.txt

What is going wrong here?

Edelfix
  • 871
  • 1
  • 7
  • 8
  • Possible duplicate of [react js handling file upload](https://stackoverflow.com/questions/39695275/react-js-handling-file-upload) – Jude Niroshan May 26 '18 at 05:59

4 Answers4

36

I've solved my problem.

  handleClick = () => {

    fetch('/sample.txt')
    .then((r) => r.text())
    .then(text  => {
      console.log(text);
    })  
  } 

Tis link did help: Fetch local JSON file from public folder ReactJS

Edelfix
  • 871
  • 1
  • 7
  • 8
26

Not wanting to use fetch as it makes me have to deal with async responses. I solved my problem like this.

  1. Created a seperate .js file and assigned my text to a variable
  2. Exported the variable
const mytext = `test
 this is multiline text.
 more text`;

export default mytext ;
  1. In my other component, I import the file.
import mytext from './mytextfile.js';
  1. I am now free to assign it to a variable or use it anywhere in my component.
 const gotTheText = mytext;
 return (<textarea defaultValue={gotTheText}></textarea>);
TBX
  • 317
  • 3
  • 2
9

This works well in practice:

import React from 'react';
import textfile from "../assets/NOTES.txt";

function Notes() {
  const [text, setText] = React.useState();
  fetch(textfile)
    .then((response) => response.text())
    .then((textContent) => {
      setText(textContent);
    });
  return text || "Loading...";
}
Simon B.
  • 2,530
  • 24
  • 30
  • Is there a way to do this while preserving line breaks? – Austin Poulson Jul 29 '23 at 23:32
  • 1
    I found placing it in the public folder and then passing the path to fetch also works. In my case it was an excel file and importing it like this did not work, unfortunately. "Cannot find module '../../public/words.xlsx' or its corresponding type declarations.ts" – Muhammad Mubashirullah Durrani Jul 30 '23 at 09:11
2

You should use a json file instead:

sample.json:

{
  "text": "some sample text"
}

component:

import { text } from './sample.json';

console.log(text); // "some sample text"
Roy Wang
  • 11,112
  • 2
  • 21
  • 42
  • 4
    Thank you for answer but it as a .txt file. I have no chose. Is there a way to convert a text file to json file or is there no other way as json format? – Edelfix May 26 '18 at 08:40
  • Why can't you convert it to `json`? Can you explain your use case / circumstances? – Roy Wang May 26 '18 at 08:50
  • 1
    The.txt is just one example. I am trying to create an application to display a GEDCOM file. My GEDCOM file changes again and again. I want the file to be loaded and displayed on startup. So load the GEDCOM file and convert it to string and display it. – Edelfix May 27 '18 at 12:18
  • 1
    u can write a script to automate the conversion to json before the build process, or set up a server (which will be able to read any files in the file system) to serve to the client. – Roy Wang May 27 '18 at 12:32
  • 1
    Is it always better to load a json file than a simple text file? What if you want to load a muli-line string, as declared between back-ticks? Using json in this case seems less convenient than the solution suggested by @Edelfix ... ` multiline multiline multiline ` – Francis Nov 29 '18 at 08:55
  • Using JSON results in the content being bundled with the JS. Using text file requires an additional http request to the server, which can be an advantage if the text file is large and its content is not necessary for the initial render. So it depends on your use case. – Roy Wang Nov 29 '18 at 09:25