Categories
React Answers

How to Delete an Item from a State Array in a React Component?

Spread the love

Sometimes, we want to delete an item from a state array in a React component.

In this article, we’ll look at how to delete an item from a state array in a React component.

Delete an Item from a State Array in a React Component

We can return a new array within the state setter function’s callback to change a React component’s state array.

For instance, we can write:

import React, { useState } from "react";

export default function App() {
  const [names, setNames] = useState(["jane", "john", "james"]);

  return (
    <div className="App">
      <button
        onClick={() =>
          setNames((names) => names.filter((_, i) => i !== names.length - 1))
        }
      >
        delete
      </button>
      <div>{names.join(", ")}</div>
    </div>
  );
}

We have the names state array that we created with useState .

Then we have a button that has the onClick prop set to a function that calls setNames with a callback that returns the names array without the last element.

We remove the last element from the returned array by calling filter with a callback that checks whether i isn’t names.length — 1 .

This will update the names array with the array returned by filter .

And below that, we render the names entries in a string.

Now when we click on the button, we see the last name in the string removed.

Conclusion

We can return a new array within the state setter function’s callback to change a React component’s state array.

By John Au-Yeung

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

Leave a Reply

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