简体   繁体   中英

How to delete specific list item in React Hooks / Redux app?

I got ListComponent where I want all the todo items to be displayed from my redux store.

Question is, how can I know which particular list item I want to be deleted by clicking the button next to it?

My ListComponent looking like this:

const ListComponent = () => {

  const todoArray = useSelector(state => state.todos);
  const dispatch = useDispatch();

  const title = todoArray.length === 0 ? 'You have nothing to do?' : 'Your to do list:';

  const deleteItem = () => {

    // how can I know which item to delete?
    
    dispatch(deleteTodo(item))
    
  }



  return ( 
    <>
      <div className="list-container">
        <div className="title-container">
          <h3> {title} </h3>
        </div>
        
          <div className="ul-container">
            <ul className="todo-list">

              {todoArray.map((item, i) => ( 
                <li 
                  key={i}
                  id={i}
                >
                  <p>{item} {i}</p> 
                  <span> Utworzono 21.11.2020 o 9:20</span>
                  <div className="action-buttons-container">

                    <button onClick={deleteItem} className="btn btn-sm btn-outline-danger" alt="delete">
                      <FontAwesomeIcon icon={faTrashAlt} /> 
                    </button>

                  </div>
                  
                </li>
                ))}
                
            </ul>
          </div>
      </div>
    </>
  );
}

You need to pass the id reference when you click the delete item, so after you know which item you have to delete.

To do so, add in your function the id or any reference you want to use to recognize it like so

   // in your .map add the id reference as parameter
   <button onClick={() => deleteItem(item.id)} className="btn btn-sm btn-outline-danger" alt="delete">


//In your function

  const deleteItem = (itemId) => {

    // if you gonna filter the item in your action  
    dispatch(deleteTodo(itemId))

    // if you want to filter now and directly send the item to delete
    const item = todoArray.find((item) => item.id === itemId)
    dispatch(deleteTodo(item))    
  }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM