I was practicing todo list in React and I faced a problem that I don't understand. Can't delete the item from the array that is in my state. I'm passing the index to my delete function and than I was trying to filter through the array to set a new State.
Here is the code of my App component:
class App extends React.Component {
state = {
tasks : []
}
addToScreen = (task) => {
const tasks = { ...this.state.tasks }
tasks[`task${Date.now()}`] = task
this.setState(prevState => ({
tasks: [...prevState.tasks, task]
}))
}
deleteTask = index => {
const reducedArr = this.state.tasks.filter( (item) => {
return item[index] !== item
})
this.setState({
tasks: reducedArr
})
}
render() {
return (
<>
<Input addToScreen={this.addToScreen}/>
<Screen tasks={this.state.tasks} deleteTask={this.deleteTask}/>
</>
);
}
}
And here is my Screen component:
class Screen extends React.Component {
render() {
return (
<ul>
{this.props.tasks.map((key, index) => <li key={index}>{key}
<button onClick={() => this.props.deleteTask(index)}>x</button>
</li>)}
</ul>
)
}
}
So it when you press the button on my screen component it should remove the specific value from the state. Thanks for help or any tips!