Home > database >  Trying to read an array from a file in React, but it comes up undefined
Trying to read an array from a file in React, but it comes up undefined

Time:07-05

I'm new to React and am working on a small project. I'm trying to figure out why React won't read the data from my dataArray.js file. It comes up undefined when I console.log it. I made sure the data was being exported, the data was connected to the App.js file, and I have the data listed in the state.

I'm stumped as to what else to try.

import "./styles.css";
import { receiptsData } from "./dataArray";
import { Component } from "react";
import Receipt from "./components/Receipt";

class App extends Component {
  state = {
    receiptsData
  };
  render() {
    console.log(receiptsData);
    return (
      <div className="App">
        <Receipt receipts={this.state.receiptsData} />

      </div>
    );
  }
}
export default App;

I have a copy on condesandbox.io: https://codesandbox.io/s/korillaapp-0pm5y3

I know I'm getting other errors as well, but I think it's tied to not being able to read the data from the dataArray.js file.

CodePudding user response:

You have a default export in dataArray.js and named import in App.js.

So or do export const receiptsData = ... in dataArray.js, or import it as import receiptsData from "./dataArray"; in App.js

CodePudding user response:

You exported your array as default export, so it should be imported like this :

import receiptsData from "./dataArray";

Or change your export like this :

export const receipts = [...]

CodePudding user response:

1) Replace Receipt.js with below code

import ReceiptItem from "./ReceiptItem";

const Receipt = (props) => {
  const { receipts } = props;
  const receiptList = receipts.map((receipt, idx) => {
    return(<div>
      <ReceiptItem receipt={receipt} key={idx} />
    </div>);
  });
  return (
    <div>{receiptList}</div>
  )
};
export default Receipt;

2) Add below line of code in the last in ReceiptItem.js

export default ReceiptItem;

3) You have default export receiptsData from dataArray.js so use receiptsData with {} in App.js

  • Related