I am making a To-Do Application in React. I got stuck at some point.
I'm mapping through items in an array, and displaying it in an unordered list. I'm trying to use the filter function, to remove the deleted items from the array.
I assume that the problem in my code can be somewhere there, that I am passing the event object but pointing to the button, instead of the list item.
How can I do it in React? You can find my code attached below.
Also it would be great to clear the input field after submitting an item.
import React, { Component } from 'react';
class ToDoList extends Component {
constructor(props) {
super(props);
this.state = {list: [], items: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleRemove = this.handleRemove.bind(this);
}
handleChange(event) {
this.setState({items: event.target.value})
console.log(event.target.value);
}
handleSubmit(event) {
this.setState({ list: [...this.state.list, this.state.items]})
event.preventDefault();
}
handleRemove(event) {
const filteredArray = this.state.list.filter(item => item !== event.target.value)
this.setState({list: filteredArray});
console.log(event.target);
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
<input
type="text"
value={this.state.value}
onChange={this.handleChange} />
</label>
<input
onClick={this.handleSubmit}
type="submit"
value="Submit" />
</form>
<ul>
{this.state.list.map((i, index) => (
<li key={index+1}>
{i}
<button
onClick={this.handleRemove}>
X
</button>
</li>
))}
</ul>
<p>Remaining: {this.state.list.length}</p>
</div>
);
}
}
export default ToDoList;