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

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.