Categories
JavaScript Answers

How to removing element from array in component state with React?

Spread the love

Sometimes, we want to removing element from array in component state with React.

In this article, we’ll look at how to removing element from array in component state with React.

How to removing element from array in component state with React?

To removing element from array in component state with React, we use the filter method.

For instance, we write

//...

class Comp extends React.Component {
  //...
  removeItem = (index) => {
    this.setState({
      data: this.state.data.filter((_, i) => i !== index),
    });
  };
  //...
}

to add the removeItem method into the Comp component that sets the data state to an array set as the original value of the data state but without the item at index.

We call filter with (_, i) => i !== index to return an array without the index.

Conclusion

To removing element from array in component state with React, we use the filter method.

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 *