Removing items is important too

If we're adding items, we should remove them too, so we'll implement a removeTodo() function in the TodoList, and then that will get passed down into each Todo. This is very similar to what we did in the NewTodo component. We'll need to follow the same steps: add a bind statement, write the removeTodo() function, and implement calling it in the Todo component.

First, the bind in src/TodoList.js is as follows:

  constructor(props) {
super(props);
this.state = { items: ['Item #1', 'Item #2', 'Item #3'] };

this.addTodo = this.addTodo.bind(this);
this.removeTodo = this.removeTodo.bind(this);
}

Next, we'll implement the removeTodo() function. We'll filter out any Todos that match the item we want to remove and set that as the new list of Todos:

  removeTodo(removeItem) {
const filteredItems = this.state.items.filter(description => {
return description !== removeItem;
});
this.setState({ items: filteredItems });
}

The final thing we need to do is change the renderItems() call so that it passes this new function down to each Todo:

  renderItems() {
return this.state.items.map(description => (
<Todo
key={description}
description={description}
removeTodo={this.removeTodo}
/>
));
}

Finally, we're ready to implement this in the child component. Open up src/Todo.js, and we'll implement a duplicate-named removeTodo() function inside of the Todo component. We'll also need a bind, so we'll start this implementation in the constructor:

this.removeTodo = this.removeTodo.bind(this);

And, we'll write the removeTodo() function:

removeTodo() {
this.props.removeTodo(this.state.description);
}

The last thing we need to do is add a call, via a button and an onClick event handler, and call the component's removeTodo() function:

render() {
return (
<div className={this.cssClasses()}>
{this.state.description}
<br />
<button onClick={this.markAsDone}>Mark as Done</button>
<button onClick={this.removeTodo}>Remove Me</button>
</div>
);
}

After saving and the browser refreshing, you should now be able to add and remove items on the fly! Full interactivity! Refer to the following screenshot:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.108.54