ReactJS error when passing a function as a props

Tags: , , ,



Recently I started to learn ReactJS with help of tutorials and I’ve run into an error I can’t find solution for by myself. One of the first projects I decided to do is To-do list and when trying to pass “handleChange” function as a prop to my component I get this error TypeError: Cannot read property 'handleChange' of undefined.

Here is my full code of App class so you can see what I’m trying to do:

import React from 'react';
import './App.css';
import Content from "./Content"
import ToDoItems from "./ToDoItems"

class App extends React.Component {

  constructor() {
    super()
    this.state = {
      items: ToDoItems
    } 
    this.handleChange = this.handleChange.bind(this)
  }

  handleChange() {
    console.log("Change!")
  }

  render() {
    const items = this.state.items.map(function(item){
      return (<Content key={item.id} todo={item.item} checked={item.completed} handleChange={this.handleChange}/>)
    })
    return (
      <div>
        {items}
      </div>
    )
  }
}

export default App;

I’m getting my data from file called ToDoItems and trying to pass them as props into Content component. Everything is working fine until I try to pass the function handleChange().

I must be doing something wrong. Any help would be appreciated.

Answer

The problem is here,

const items = this.state.items.map(function(item){
      return (<Content key={item.id} todo={item.item} checked={item.completed} handleChange={this.handleChange}/>)
    })

When ur using non-array function it binds this and others stuff to its own protoype. Meaning ur this.handleChanges this actually refers to function, instead of class

Try using this,

const items = this.state.items.map((item) => {
//                                 ^^^^^^^^^^^
      return (<Content key={item.id} todo={item.item} checked={item.completed} handleChange={this.handleChange}/>)
    })

as Arrow functions don’t bind this or any other stuff. so this should now refer to the class



Source: stackoverflow