Languages
[Edit]
EN

React - how to add / remove items from array in state (class component)

0 points
Created by:
jarlh
635

In this article, we would like to show you how to add and remove items from an array in the state in React.

Below example presents two functions:

  • handleAddItem that uses spread operator (...) to create a copy of array in the state, adds an item to it and then with setState() method updates the state value.
  • handleRemoveItem that uses filter() method to remove item with the last index from the array.

Runnable example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: []
    };
  }

  handleAddItem = () => {
    const items = this.state.items;
    this.setState({ items: [...items, 'item-' + items.length] });
  };

  handleRemoveItem = () => {
    const items = this.state.items;
    if (items.length > 0) {
      const lastIndex = items.length - 1;
      this.setState({ items: items.filter((item, index) => index !== lastIndex) });
    }
  };

  render() {
    const items = this.state.items;
    return (
      <div className="wrapper">
        <div>
          List: {items.length} total items.
        </div>
        <button onClick={this.handleAddItem}> Add</button>
        <button onClick={this.handleRemoveItem}>Remove</button>
        <ul>
          {items.map((item, index) => <li key={index}>{item}</li>)}
        </ul>
      </div>
    )
  }
}

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

Note:

Go to this article to see functional component example.

References:

Alternative titles

  1. React - how to update array in state (class component)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - add / remove items from array in state (class component)
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join