0

Let's say I have an array and I'm mapping through it:

{items &&
      items.map((item) => (
        <div key={item}>
          {item} <button>Delete</button>
        </div>
      ))}

I'm keeping items in state hook - [items, setItems] = useState(itemsArray); How do I remove the item at its specific index when I click that 'Delete' button?

Steph
  • 443
  • 2
  • 4
  • 15
  • Welcome to Stack Overflow! Please take the [tour] if you haven't already (you get a badge!), have a look around, and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) I also recommend Jon Skeet's [Writing the Perfect Question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) and [Question Checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Please [**search thoroughly**](/search?q=%5Bjs%5D+%5Breactjs%5D+remove+item+from+array) before posting. More about searching [here](/help/searching). – T.J. Crowder Feb 02 '22 at 15:11
  • Thanks but the post you linked to has much more complicated syntax. Can't understand why this is considered a duplicate. – Steph Feb 02 '22 at 15:12
  • It's the same thing. An array, and a call to remove something from the array. The examples there are not over-complicated. – T.J. Crowder Feb 02 '22 at 15:13
  • Yes but mine is the more general case so I don't see why this shouldn't coexist with the specific case. The examples are not over complicated because you probably already know how to code but for someone learning it makes a whole lot of difference. – Steph Feb 02 '22 at 15:30
  • 1
    SO's model is designed around **not** having a thousand copies of the same question, each with different answers. (Sadly, though, if you search, you'll find at least a dozen copies of "how do I remove an item from an array in React" anyway, this topic is **very** thoroughly covered here, because people think their question is special and there's an endless supply of people posting repeated questions.) Fundamentally, `setItems(items => items.filter((item, index) => index !== indexToRemove);` [Example search](/search?q=%5Bjs%5D+%5Breactjs%5D+remove+item+by+index). – T.J. Crowder Feb 02 '22 at 15:44
  • (Oops, missing `)` on that. :-) ) – T.J. Crowder Feb 02 '22 at 15:51

0 Answers0