2

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

1
  • Todos is expecting a todos props but you didn't pass it from your App. Just change it to <Todos todos={this.state.todos}/> Commented Jan 12, 2019 at 12:39

2 Answers 2

3

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

You must pass in a property like so:

<Todos todos={this.state.todos} />
Sign up to request clarification or add additional context in comments.

2 Comments

thanks I thought when I call Todos like this <Todos /> it will run on app.js and since its return is return this.props.todos.map((todo) this will get the state and the array in it called todos
The component only "knows" about properties in its own class, so you need to pass down data from parent components that you want available in the children.
0

In your App.js call the todos from the state

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

It should work fine after that

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.