When we add a bill we could make an error, so it’s handy to have the option to delete one.

We’ll do that by adding an “X” next to each line in the table.

Let’s add the markup first, in the BillsTable component, where we loop on bills, we add another td element, which contains a button with a click event handler:

{props.bills.map((value, index) => {
  return (
    <tr className="p4" key={index}>
      <td>
        <Moment format="MMM D YYYY">{value.date}</Moment>
      </td>
      <td>${value.amount}</td>
      <td>{value.category}</td>
      <td>
        <button onClick={() => removeBill(index)}>𝗫</button>
      </td>
    </tr>
  )
})}

Notice how we can pass a parameter to the method so we can tell it which bill to delete. To do so we need to use an arrow function, otherwise the removeBill() method is immediately called, since we added the parentheses.

Let’s define the removeBill method:

const removeBill = index => {
  props.removeBill(index)
}

We escalate the event to the parent, the App component so it can handle removing it from the bills list:

<BillsTable
  bills={bills}
  showAddBill={showAddBill}
  removeBill={removeBill}
/>

Here’s the method:

const removeBill = index => {
  let updatedBills = [...bills]
  updatedBills = updatedBills
    .slice(0, index)
    .concat(updatedBills.slice(index + 1, updatedBills.length))
  setBills(updatedBills)
  localStorage.setItem('bills', JSON.stringify(updatedBills))
}

See, we remove an item from bills by concatenating two portions of the array, one until the element we want to remove, and one from the next element till the end. We also update the local storage to reflect the changes.

See the app in the current state on CodeSandbox.


Go to the next lesson