DEV Community

Syazwan
Syazwan

Posted on

How to Remove an Item from an Array in React State

Removing an item from an array in React state is straightforward using the filter method. This method creates a new array without the specified item.

Example

Initial Array:

const arr = [1, 2, 3];
Enter fullscreen mode Exit fullscreen mode

Create a New Array without the Item:

const new_arr = arr.filter((item) => item !== 2);
Enter fullscreen mode Exit fullscreen mode

Result:

console.log(new_arr); // [1, 3]
Enter fullscreen mode Exit fullscreen mode

Implementation in React

Delete items in React

State Initialization

The state items is initialized with an array of strings.

const [items, setItems] = useState([
  "Item One",
  "Item Two",
  "Item Three",
  "Item Four",
  "Item Five",
]);
Enter fullscreen mode Exit fullscreen mode

Removing an Item

The removeItem function uses setItems to update the state. It filters out the item to be removed by creating a new array that excludes the specified item.

const removeItem = (itemToRemove) => {
  setItems((prevItem) => prevItem.filter((item) => item !== itemToRemove));
};
Enter fullscreen mode Exit fullscreen mode

Rendering Items

The items are mapped to display each one with a Delete button. Clicking the button triggers removeItem to update the state.

<div className="p-8 flex flex-col gap-4 items-start">
  {items.map((item) => (
    <div key={item} className="text-sm flex border px-2 py-1 items-center">
      <p className="w-32">{item}</p>
      <button
        className="border rounded bg-red-600 p-1 text-slate-200"
        onClick={() => removeItem(item)}
      >
        Delete
      </button>
    </div>
  ))}
</div>
Enter fullscreen mode Exit fullscreen mode

Full code

import { useState } from "react";

export default function App() {
  const [items, setItems] = useState([
    "Item One",
    "Item Two",
    "Item Three",
    "Item Four",
    "Item Five",
  ]);

  const removeItem = (itemToRemove) => {
    setItems((prevItem) => prevItem.filter((item) => item !== itemToRemove));
  };

  return (
    <div className="p-8 flex flex-col gap-4 items-start">
      {items.map((item) => (
        <div key={item} className="text-sm flex border px-2 py-1 items-center">
          <p className="w-32">{item}</p>
          <button
            className="border rounded bg-red-600 p-1 text-slate-200"
            onClick={() => removeItem(item)}
          >
            Delete
          </button>
        </div>
      ))}
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Conclusion

Using the filter method in React allows you to effectively manage and update arrays in the state, ensuring a clean and efficient way to remove items.

Top comments (0)