I want to remove a task from your Todolist
. I implement a handle function that removes the desired task from the tasks
array when a delete button is clicked using the filter function. Then update the state. But if the button is clicked, the desired task does not get removed or deleted.
below is my code
import React from "react";
import { useState } from "react";
import '../App.css'
let nextId = 0;
function Todolist (){
const [tasks, setTasks] = useState([]);
const [input, setInput] = useState('')
const handleChange = (e)=>{
setInput(e.target.value);
}
const addTask = () =>{
if(input.trim()){
setTasks([...tasks, {text:input, completed: false, id: nextId++}]);
setInput('');
}
}
const deleteTask = item =>{
const newTasks = tasks.filter(task => task.id !== item.id);
setTasks(newTasks);
}
return (
<div className="todolist-container">
<h3>Big Todos</h3>
<ul>
{tasks.map((task, index) => (
<li key={index} className={task.completed? 'task completed': 'task'}>
<span>{task.text}</span>
<button onClick={deleteTask}>delete</button>
</li>
))}
</ul>
<input className="todo" type="text" value={input} onChange={handleChange}/>
<button onClick={addTask}>add</button>
</div>
)
}
export default Todolist;