1

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();
   }
 }
connexo
  • 53,704
  • 14
  • 91
  • 128
  • Possible duplicate of [React: "this" is undefined inside a component function](https://stackoverflow.com/questions/33973648/react-this-is-undefined-inside-a-component-function) – ponury-kostek Nov 06 '18 at 17:10

1 Answers1

2

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 :)

Nikko Khresna
  • 1,024
  • 8
  • 10
  • As stated above you have to bind or use an arrow function. But I don't se that you passing along the item into your actual delete method. So this won't delete anything if you don't fix that. It takes the item as parameter and has to know what item to delete so you have to pass that along also. – weibenfalk Nov 06 '18 at 17:14