Home » Javascript » React.js – array not displaying correctly after getting strings from textfile

React.js – array not displaying correctly after getting strings from textfile

Posted by: admin August 19, 2018 Leave a comment

Questions:

I’m working on a program in React.js, and I’m having trouble getting of the arrays to display correctly. I’ve tried various “join” statements, none of which seem to do the trick. I’ve tried splitting the lines by using split(/\r?\n/).
I’m using the Fetch API to call a text file and then put the contents into an array, which I then want to display to the screen. If anyone can give any pointers as to why it might not be working, please point them out!

Here’s my code:

cats.txt

Persian
Himalayan
Siamese
Sphynx

App.js

import React, { Component } from 'react';
import "Cat" from "./components/Cat.js";
import catFile from "cats.txt";

class App extends Component {
  state = {
      cat_Array: []
    }
    getCats = (e) => {
      e.preventDefault();
        fetch(catFile).then(data => data.text()),
        .then(allResponses => {
          let catArray = allResponses.split(/\r?\n/);
this.setState({
                    cat_array: catArray
                  })
            }
          }
        })
      }
  render() {
    return (
      <div>
      <h2> Cats</h2>
      <Cats
        getCats={this.getCats}
        />

      </div>
    );
  }
}

components/Cat.js

import React from 'react';

class Cat extends React.Component {
    render() {
        return (
            <div>
               <p> {this.props.getCats} </p>
            </div>)
    }
}

export default Cat;

Actual Output

PersianHimalayanSiameseSphynx

Expected Output

Persian
Himalayan
Siamese
Sphynx
Answers: