I am currently studying React.js and I am not familiar with React.js. I am making a simple todo app just to study 'CRUD' operation and I tried hard to make a task delete when a button is clicked. I heard that it is done by filter method. As I said, I am not familiar with React.js, So I can't Delete the task using filter method.
Here Is My Code
JSX
import "./style.css";
import { useState } from "react";
function App() {
const [toDos, setToDos] = useState([]);
const [toDo, setToDo] = useState("");
return (
<div className="app">
<div className="mainHeading">
<h1>ToDo List</h1>
</div>
<div className="subHeading">
<br />
<h2>Whoop, it's Wednesday 😀 ☕ </h2>
</div>
<div className="input">
<input
value={toDo}
onChange={(e) => setToDo(e.target.value)}
type="text"
placeholder="🖊️ Add item..."
/>
<i
onClick={() =>
setToDos([...toDos, { id: Date.now(), text: toDo, status: false }])
}
className="fas fa-plus"
></i>
</div>
<div className="todos">
{toDos.map((obj) => {
return (
<div className="todo">
<div className="left">
<input
onChange={(e) => {
console.log(e.target.checked);
console.log(obj);
setToDos(
toDos.filter((obj2) => {
if (obj2.id === obj.id) {
obj2.status = e.target.checked;
}
return obj2;
})
);
}}
value={obj.status}
type="checkbox"
name=""
id=""
/>
<p>{obj.text}</p>
</div>
<div className="right">
<i onClick={this.props.deleteTodo} className="fas fa-trash"></i>
</div>
</div>
);
})}
{toDos.map((obj) => {
if (obj.status) {
return <h1 className="finished">{obj.text}</h1>;
}
return null;
})}
</div>
</div>
);
}
export default App;
Please Tell Me A Solution For This
In your onClick handler you can pass the current todo Objects id which you want to delete
onClick ={() => deleteTodo(obj.id)}
Now in your deleteTodo function you can do
const deleteTodo = idToDelete => setTodos(currentTodos => currentTodos.filter(todo => todo.id !== idToDelete))
Note i have removed this.props
from the deleteTodo. You are using a functional component. So you should not be using this
to access the props.
So your code has to be like this
function App() {
const [toDos,setToDos] = useState([])
const [toDo,setToDo] = useState('')
const deleteTodo = idToDelete => setTodos(currentTodos => currentTodos.filter(todo => todo.id !== idToDelete))
return (
....
<div className="right">
<i onClick ={() => deleteTodo(obj.id)} className="fas fa-trash"></i>
</div>
</div>)
...
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.