Categories
JavaScript Answers

How to delete an item from list with React and JavaScript?

Spread the love

Sometimes, we want to delete an item from list with React and JavaScript.

In this article, we’ll look at how to delete an item from list with React and JavaScript.

How to delete an item from list with React and JavaScript?

To delete an item from list with React and JavaScript, we can use some array methods.

For instance, we write:

import React from "react";

const arr = [
  { id: 1, name: "apple" },
  { id: 2, name: "orange" },
  { id: 3, name: "grape" }
];

export default function App() {
  const [items, setItems] = React.useState(arr);

  const deleteItem = (index) => () =>
    setItems((items) => items.filter((_, i) => i !== index));

  return (
    <>
      {items.map((it, index) => {
        return (
          <div key={it.id}>
            {it.name} <button onClick={deleteItem(index)}>delete</button>
          </div>
        );
      })}
    </>
  );
}

to create the items state with useState.

Then we define the deleteItem function that takes the index of the item to delete and returns a function that calls setItems with (items) => items.filter((_, i) => i !== index) to set items to an array that doesn’t include the item in items at index.

Next, we call items.map to render the items with a delete button in each entry.

We set the onClick prop of the button to the function returned by deleteItem when called with the index.

Conclusion

To delete an item from list with React and JavaScript, we can use some array methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

2 replies on “How to delete an item from list with React and JavaScript?”

Leave a Reply

Your email address will not be published. Required fields are marked *