Aquestion
Aquestion

Reputation: 23

How to fix 'TypeError: Cannot read property 'map' of undefined' in React

Hello I am new in React and trying to display the array called Todo that I have created in state, However I get the error "TypeError: Cannot read property 'map' of undefined". Can you please tell me where I have done wrong?

Here is my code

index.js

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

import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

serviceWorker.unregister();

App.js

import React, { Component } from 'react';
import Todos from './component/Todos.js';
import './App.css'

class App extends Component {
  state={
    todos:[
        {
            id: 1,
            title:'Star Wars',
            point:9,
            watched: true
        },
        {
            id: 2,
            title:'Into the Wild',
            point:null,
            watched: false
        },
        {
            id: 3,
            title:'Enter the Void',
            point:6,
            watched: true
        },
        {
            id: 4,
            title:'Tschick',
            point:7.5,
            watched: true
        }
    ]
  }
  render() {
    return (
      <div className="App">
       <Todos />
      </div>
    );
  }
}

export default App;

Todo.js

import React, { Component } from 'react';


class Todos extends Component {

  render() {

    return this.props.todos.map((todo) => (
        <div>
        <h3>{todo.title}</h3>
        </div>
    ));
  }
}


export default Todos;

The error that I get

Upvotes: 2

Views: 2922

Answers (2)

anandpotukuchi
anandpotukuchi

Reputation: 1

In your App.js call the todos from the state

<Todos todos={this.state.todos}/>

It should work fine after that

Upvotes: 0

Tim Klein
Tim Klein

Reputation: 2758

You aren't passing the todos variable to your component.

You must pass in a property like so:

<Todos todos={this.state.todos} />

Upvotes: 3

Related Questions