I am trying to learn react js , but I don’t know how to delete an item from my list, could you help me ? Actually, I am not professional , but I am really interested in learning, there is my codes which add some new item to my list properly, but I don’t know how to delete them when I click on their checkbox/delete button.
import React, { useState } from "react"; const App = () => { const [NewTaskText, setNewTaskText] = useState(""); const [Tasks, setTasks] = useState(["do a task", "samira"]); const addTask = (e) => { e.preventDefault(); if (!NewTaskText) return; setTasks((currentTasks) => { return [...currentTasks, NewTaskText]; }); setNewTaskText(""); }; const onchangeInput = (e) => { const value = e.target.value; setNewTaskText(value); }; return ( <div className="row"> <form onSubmit={addTask}> <div className="row col s6"> <div className="input-field col s10"> <textarea id="textarea1" className="materialize-textarea" value={NewTaskText} onChange={onchangeInput} ></textarea> <label htmlFor="textarea1">What needs to be done ?</label> </div> </div> <div className="row col s6"> <br></br> <a className='waves-effect waves-light btn' href="/#" onClick={addTask}> <i className='material-icons left' > add_circle </i> Add </a> </div> </form> <div className="row"> <div className="row col s9"> <ul className="collection with-header"> <li className="collection-header"> <h4>Todo List</h4> <form> <div className="input-field"> <input id="search" type="search" required /> <label className="label-icon" htmlFor="search"> <i className="material-icons">search</i>Search </label> <i className="material-icons">close</i> </div> </form> </li> <label> {Tasks.map((item, i) => { return ( <li className="collection-item" key={i}> <input type="checkbox" /> <span> {item} </span> <span> <a href="#!" className="secondary-content"> <i className="material-icons" >delete</i> <i className="material-icons">check_circle</i> </a> </span> </li> ); })} </label> </ul> </div> </div> </div> ); }; export default App;
Advertisement
Answer
You can delete the item from the array by using index:
<i className="material-icons" onClick={() => handleDelete(i)}>delete</i>
and define your function above the return statement:
const handleDelete = i => { const taskList = [...Tasks] taskList.splice(i, 1) setTasks(taskList) }
Here it is important to know that you have to make a copy of the state if it is an object
or an array
. Because if you modify the original array or object, react won’t register that as a change, and won’t re-render. That is why I did const taskList = [...Tasks]
. You can also use a library like lodash
which provides some neat ways of handling objects and arrays