Delete Items from state array in React


Previously we learned how to render a list of items in React. Today we’ll be focusing on how to delete items from state array. The idea is to show that React will recognise these changes as the list changes and update the UI accordingly.

Setting up the React Component

Start by creating a new React component or using an existing one where you want to manage the list of items. Define the initial state with an array to hold the list items.

import React, { useState } from 'react';

const ListComponent = () => {
  const [items, setItems] = useState(['Item 1', 'Item 2', 'Item 3']);

  // Rest of the component code
};

Rendering the List

Next, we’ll render the list of items in the component’s return statement. Make sure to include a way to delete each item, such as a delete button or an icon.

const ListComponent = () => {
  // ...state initialization

  const handleDeleteItem = (index) => {
    // Logic to remove the item from the list
  };

  return (
    <div>
      <h2>List of Items:</h2>
      <ul>
        {items.map((item, index) => (
          <li key={index}>
            {item}
            <button onClick={() => handleDeleteItem(index)}>Delete</button>
          </li>
        ))}
      </ul>
    </div>
  );
};

Deleting Items By Filtering

As discussed in my previous article, React does not want you to directly mutate the state of the array. So in order to remove an item, filtering is a good choice. Let’s look at two ways to use filter to remove items.

const arr = ["1", "2", "3"]; // create a constant array
const valueToRemove = "2"; 
const indexToRemove = 0;

// example 1: filter out the index of the array
const newArr = arr.filter((value,index) => {
  if (indexToRemove != index) {
    return value;
  }
})

console.log(newArr);

// example 2: filter out the value to remove
const newArr2 = arr.filter(value => value != valueToRemove);

console.log(newArr2);

Implementing the Delete Functionality

Now, let’s implement the handleDeleteItem function. This function will take an index as an argument and update the state to remove the corresponding item.

const ListComponent = () => {
  // ...state initialization

  const handleDeleteItem = (index) => {
    const updatedItems = items.filter((value,arrIndex) => {
      if (arrIndex != index) { // if the passed in index doesn't equal the current index then we want to keep this
        return value;
      }
    })   
    setItems(updatedItems);
  };

  // ...rendering and other code
};

Test the Component

At this point, your component should be ready to delete items from the list. When you click the “Delete” button next to an item, it should disappear from the list as the state is updated.

And that is how you can delete items from your lists in React. Don’t forget to check out my other React articles here.

You can follow me on Twitter here

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments