Madan Hegde
Madan Hegde

Reputation: 43

TypeError: this is undefined; can't access its "props" property

My todo app goes like this...and..I'm trying to remove the particular todo item out of the list. I'm calling a function from the child component passing another function as a prop. the problem is, whenever I call the function in child component it fails to access the props in the parent component which is also a function. I tried 'bind'ing the map function called in the parent component. But still in vain. How can I solve this or is there any better way to delete todo-item?? Need help! Thanks in advance!

Here is the snapshot of the error

class Todo extends Component {

//initializing state
constructor(props) {
super(props);
this.state = {
  todoList: ['wash clothes', 'water the garden', 'buy some flowers', 'something else!']
 }
}

//rendering and cycling through the data (toodoList)
render() {
var todoList = this.state.todoList;
todoList = todoList.map(function(item, index) {
  return(
    <TodoItem item={item} onDelete={this.handleClick.bind(this)} key={index} />
  );
}, this);

return(
  <div className="component-body">
    <AddItem />
    <ul>
      {todoList}
    </ul>
  </div>
);
  }

  //removing item
 handleClick(item) {
    var updatedList = this.state.todoList.filter(function(val, index){
  return item !== val;
});
this.setState= {
  todoList: updatedList
  }
}
 }
class TodoItem extends Component {
 render() {
  return(
    <li>
     <div>
       <span> {this.props.item} </span>
       <span className="handle-delete" onClick={this.handleClick}> x </span>
     </div>
   </li>
       );
     }
 //Custom function
    handleClick() {
      this.props.onDelete();
   }
 }

Upvotes: 1

Views: 882

Answers (1)

Nikko Khresna
Nikko Khresna

Reputation: 1009

You have to use arrow function

handleClick = () => {

Or if you cant use it, Define a constructor in the class where the method is, then inside it: this.handleClick().bind(this)

This way, this you are refering to, and this the method refers to, is the same. Lets say it's miscommunicate between you and the method :)

Upvotes: 2

Related Questions