I am a new to React and trying to make a toDoApp. I’m trying to create an onClick event to remove an element from the tasks state. But it does not seem to work. And can I also ask how to implement id keys so that I can remove the desired task that I want?
import React from 'react';
import './App.css';
class App extends React.Component {
constructor(){
super();
this.state = {
value: '',
tasks: []
};
this.handleChange = this.handleChange.bind(this)
this.addItem = this.addItem.bind(this)
this.removeItem = this.removeItem(this)
}
handleChange(event) {
this.setState({
value: event.target.value
})
}
addItem(){
if(this.state.value === ''){
alert('Enter a task!')
} else {
const newTask = [...this.state.tasks, this.state.value]
this.setState({
tasks: newTask,
value: ''
})
}
}
removeItem(){
this.state.tasks.pop()
this.setState({
tasks: this.state.tasks,
})
}
render(){
const itemList = this.state.tasks.map((num) =>
<li>{num}</li>
);
return(
<div>
<input type="text" value={this.state.value} onChange={this.handleChange}></input>
<button onClick={this.addItem}>+</button>
<button onClick={this.removeItem}>-</button>
<ul>{itemList}</ul>
{this.state.tasks}
</div>
)
}
}
export default App;
strong text