DGB
DGB

Reputation: 1342

React app failing to display list from objects. Getting this error: TypeError: Cannot read property '0' of undefined

I am doing a React course here and the starter files keep giving me this error:

TypeError: Cannot read property '0' of undefined

From this starter code:

import React from 'react'
import ReactDOM from 'react-dom'

const notes = [
  {
    id: 1,
    content: 'HTML is easy',
    date: '2019-05-30T17:30:31.098Z',
    important: true
  },
  {
    id: 2,
    content: 'Browser can execute only Javascript',
    date: '2019-05-30T18:39:34.091Z',
    important: false
  },
  {
    id: 3,
    content: 'GET and POST are the most important methods of HTTP protocol',
    date: '2019-05-30T19:20:14.298Z',
    important: true
  }
]

const App = (props) => {
  const { notes } = props

  return (
    <div>
      <h1>Notes</h1>
      <ul>
        <li>{notes[0].content}</li>
        <li>{notes[1].content}</li>
        <li>{notes[2].content}</li>
      </ul>
    </div>
  )
}

ReactDOM.render(
  <App notes={notes} />,
  document.getElementById('root')
)

Above code shows:

Attempted import error: './App' does not contain a default export (imported as 'App')

I tried amending by adding export default app and received:

TypeError: Cannot read property '0' of undefined

How can I solve this problem?

Upvotes: 0

Views: 107

Answers (1)

ravibagul91
ravibagul91

Reputation: 20765

The code from link you are referring is the complete index.js file only.

If you want your code to be modular and want to separate out App component, in that case, you should do this,

index.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import App from "./App";   //import your component (imported without { }, because App component exported as default)

const notes = [
  {
    id: 1,
    content: 'HTML is easy',
    date: '2019-05-30T17:30:31.098Z',
    important: true
  },
  {
    id: 2,
    content: 'Browser can execute only Javascript',
    date: '2019-05-30T18:39:34.091Z',
    important: false
  },
  {
    id: 3,
    content: 'GET and POST are the most important methods of HTTP protocol',
    date: '2019-05-30T19:20:14.298Z',
    important: true
  }
]

//Pass the props here
render(<App notes={notes}/>, document.getElementById('root'));

App.js

import React from 'react'

const App = (props) => {
  const { notes } = props

  return (
    <div>
      <h1>Notes</h1>
      <ul>
        <li>{notes[0].content}</li>
        <li>{notes[1].content}</li>
        <li>{notes[2].content}</li>
      </ul>
    </div>
  )
}

export default App

Demo

Upvotes: 1

Related Questions