0

I've recently started out with reactjs and have been following a tutorial with freeCodeCamp.org. This is my first post here. Let me know if any more info is needed.

I'm receiving this error: Uncaught TypeError: Cannot read property 'handleChange' of undefined despite binding handleChange() inside the constructor. Here is the snippet:-

class Todo extends Component {
  constructor(props) {
    super(props);
    this.state = { todos: TodoData };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(id) {
    console.log("Change", id);
  }

  render() {
    const TodoComps = this.state.todos.map(function (item) {
      return (
        <TodoItem key={item.id} item={item} handleChange={this.handleChange} />
      );
    });
    return <div>{TodoComps}</div>;
  }
}
export default Todo;
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
  • 2
    The problem isn't anything to do with `handleChange` it is that `this` is undefined within the `map` callback. The simplest solution is to make the callback an arrow function `map((item) => {...`. This will put `this` within scope. – Brian Thompson Aug 24 '20 at 16:11
  • 2
    Also just as a tip for using Stack Overflow - try to title your question so that it is a summary of the actual problem or at least provides good context for it. The tag tells us that its about React, and being a beginner project doesn't add any information about the problem. A good descriptive title will help attract better answers. – Brian Thompson Aug 24 '20 at 16:15
  • 2
    Does this answer your question? [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Emile Bergeron Aug 24 '20 at 16:21
  • @BrianThompson Thanks a lot for the solution and the tip! – theFeistyDev Aug 24 '20 at 16:35

0 Answers0