Search code examples
javascriptreactjscreate-react-appreact-bootstrap

In react, how to remove specific item from list


I have a list that I've created as I add items to it:

  const addToPool = () => {
    setDiePool([
      ...diePool,
      {
        dp1 : poolCount,
        dp2 : diceType,
        dp3 : diceNumber,
        dp4 : diceAdjuster
      }
    ]);

    setPoolCount(poolCount+1);
  };

Now I want to remove a specific item from the list. I have all the items displaying in a table, with a delete icon next to each one. When I click on the trash icon, I want to remove it from the list. Its not working, but not throwing any errors either. Not sure what I'm doing wrong.

my table:

      <tbody>
            {diePool.map(die => (<tr key={die.dp1}><td><FaDice /></td><td>{die.dp1}</td><td>{die.dp2}</td><td>{die.dp3}</td><td>{die.dp4}</td><td><button dp1={die.dp1} onClick={handleRemoveItem}><FaTrashAlt /></button></td></tr>))}
      </tbody>

my remove code:

  const [list, updateList] = useState(diePool);
  const handleRemoveItem = (e) => {
     const dp1 = e.target.getAttribute("dp1")
     updateList(list.filter(diePool => diePool.dp1 !== dp1));
   };

Solution

  • Try to pass die to handleRemoveItem as params, this should work:

    import React from "react";
    import ReactDOM from "react-dom";
    
    
    function App() {
      const [diePool, setDiePool] = React.useState([
        {
          dp1: "poolCount",
          dp2: "diceType",
          dp3: "diceNumber",
          dp4: "diceAdjuster"
        },
        {
          dp1: "poolCount1",
          dp2: "diceType1",
          dp3: "diceNumber1",
          dp4: "diceAdjuster1"
        }
      ]);
    
      const handleRemoveItem = die => {
        setDiePool(diePool.filter(diePool => diePool.dp1 !== die.dp1));
      };
      return (
        <div className="App">
          {diePool.map(die => (
            <tr key={die.dp1}>
              <td>
                <span>test</span>
              </td>
              <td>{die.dp1}</td>
              <td>{die.dp2}</td>
              <td>{die.dp3}</td>
              <td>{die.dp4}</td>
              <td>
                <button dp1={die.dp1} onClick={() => handleRemoveItem(die)}>
                  <span>FaTrashAlt</span>
                </button>
              </td>
            </tr>
          ))}
        </div>
      );
    }