1

Error: Uncaught TypeError: Cannot read property 'manageChange' of undefined

I have bound the method to "this" as well. I have even tried the arrow function format to define "manageChange". It still does not work.

Please help out with identifying the issue? Code:

 class App extends React.Component {
  constructor() {
    super();
    this.state = { todos: TodoData };
    this.manageChange = this.manageChange.bind(this);
  }

  manageChange(id) {
    console.log(id);
  }

  render() {
    const todoItems = this.state.todos.map(function (item) {
      return (<TodoItem key={item.id} items={item}
        handleChange={this.manageChange} />);
    }
    );
    return
    (
      <div className="app">
        {todoItems}
      </div>
    );
  }
}

2 Answers 2

2

The error is not in the definition of your manageChange function. It is instead in the below code

const todoItems=this.state.todos.map(function(item)
                {
                   return (<TodoItem key={item.id} items={item} 
                    handleChange={this.manageChange}/>);
                }
                );

You should change it to below and use arrow function instead like this

const todoItems=this.state.todos.map((item) => 
                {
                   return (<TodoItem key={item.id} items={item} 
                    handleChange={this.manageChange}/>);
                }
                );

Please note the difference in arrow function and normal function. The reference in the arrow functions is passed down to the children.

So when you define it like this; this keyword is passed as an reference of the class to this.manageChange and is not undefined.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the explanation. very new to ES6 and React and hence the confusion.
Happy to help. You can read more on ES6 features here. http://es6-features.org.
0

There is problem with map function. use arrow function in map. if you use normal function it will have it's own this which won't have manageChange function.

const todoItems=this.state.todos.map((item) =>
    {
                   return (<TodoItem key={item.id} items={item} 
                    handleChange={this.manageChange}/>);
    }
);

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.