0

I’m doing a TO-DO list tutorial in react and it was failing because I wrote something like this:

class TodoItems extends Component {
  createTasks(item) { // define it as a function
      // using “this” here breaks the app
      ...

   }
}

And the correct way to do it is

class TodoItems extends Component {
    createTask = (item) => { // using a lambda 
       // using this here is ok
       ...
     }
}

Example source code: https://github.com/therj/react-todo (specifically here)

Why is this undefined in the first one?

I tried to declare the class using the node interpreter but the prompt never returns

> class A {}
undefined
> class TodoItems /*extends Component*/ {
...     createTasks= (item) => {
.....         return (
.......             <li key={item.key} onClick={() => this.props.deleteItem(item.key)}>
.......                 {item.text}
.......
...             </li>
...         )
...     }
...
...     render() {
...         const todoEntries = this.props.entries
...         const listItems = todoEntries.map(this.createTasks)
...         return <ul className="theList">{listItems}</ul>
...     }
... }
...
...
>
(To exit, press ^C again or type .exit)

Not sure if this is react related, es6, or something else.

OscarRyz
  • 196,001
  • 113
  • 385
  • 569
  • 1
    Possible duplicate of [React: "this" is undefined inside a component function](https://stackoverflow.com/questions/33973648/react-this-is-undefined-inside-a-component-function) – UncleDave Jun 10 '19 at 21:57
  • @UncleDave that's totally the reason. Thanks. – OscarRyz Jun 10 '19 at 21:59

0 Answers0