0

I have the following text files in the same directory with my code:

Text1.txt:

This is text1

Text2.txt

This is text2

I want to make a page where when a user clicks a list, each list connects with a text file and the content of text file will be shown in the console. How do I do it?

App.js

import React, { Component } from 'react';
import './Text1.txt';
import './Text2.txt';



class App extends Component {
  constructor(props) {
    super(props);
}

  render() {
    return (
      <div>
        <h1>Text Lists</h1>
        <div>
          <h2 onClick={this.showTitle}><li>Click this to show text1</li></h2>
          <h2 onClick={this.showTitle}><li>Click this to show text2</li></h2>
        </div>
      </div>
    );
  }
}

export default App;
double-beep
  • 5,031
  • 17
  • 33
  • 41
hjk6281
  • 1
  • 1

1 Answers1

0

Assuming you are using webpack in your implementation, you will need to use file-loader to do this. You can read on how here. It's pretty simple if you have done the same with css or any other style loaders.

module.exports = {
  module: {
    rules: [
      {
        test: /\.(txt)$/i,
        loader: 'file-loader',
        options: {
          publicPath: 'assets',
        },
      },
    ],
  },
};

Once the loader is setup you should be able to import it like you would a module

import textfile from './Text1.txt';

Community
  • 1
  • 1
SpeedOfRound
  • 1,210
  • 11
  • 26