Reputation: 253
I am having trouble with my react to do list I have created. Every entry is being automatically removed on submit and it only started when I added in a remove function.
Here is the code:
import React, { Component } from 'react';
import TodoForm from './TodoForm';
import TodoItem from './TodoItem';
import './Items.scss';
export default class Items extends Component {
constructor(props) {
super(props);
this.state = {
todoItem: []
}
this.addItem = this.addItem.bind(this);
this.remove = this.remove.bind(this);
}
addItem(item) {
this.setState({
todoItem: [...this.state.todoItem, item]
});
}
remove(id) {
this.setState({
todoItem: this.state.todoItem.filter(t => t.id !== id)
});
}
render() {
const todos = this.state.todoItem.map(todo => {
return <TodoItem todo={todo.todo} key={todo.id} id={todo.id} removeTodo={this.remove}/>
});
return (
<>
<div className="items">
{todos}
</div>
<TodoForm addItem={this.addItem}/>
</>
)
}
}
Here is the code sandbox: https://codesandbox.io/s/young-sunset-lujxk?fontsize=14
Upvotes: 0
Views: 58
Reputation: 40673
You forgot to add a .bind
in your TodoItem
class. You have:
this.handleRemove = this.handleRemove(this);
but it should be:
this.handleRemove = this.handleRemove.bind(this);
as a result you are invoking the remove handler in the constructor instead of binding it to the class object.
Upvotes: 1