Languages
[Edit]
EN

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

6 points
Created by:
Dirask Community
6240

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

Note: to force React to re-render component we need to provide always new reference into setState function (const [state, setState] = ...).

Below example provides two actions:

  • Add item: that calls┬áhandleAddItem┬ámethod that┬áuses┬áspread operator (...) to create a array copy with new item that is put on the last position and┬áfinally┬ásetList()┬ámethod updates the state value - we set new reference as state.
  • Remove item: that calls┬áhandleRemoveItem┬ámethod┬áthat┬áuses┬áfilter()┬ámethod to make array copy with removed┬áindicated item (in example case it is last index) - we set new reference as state.

Runnable example:

// ONLINE-RUNNER:browser;

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

const App = () => {
  const [list, setList] = React.useState([]);

  const handleAddItem = () => {
    const items = list;
    setList([...items, `item-${items.length}`]);
  };

  const handleRemoveItem = () => {
    const items = list;
    if (items.length > 0) {
      const lastIndex = items.length - 1;
      setList(items.filter((item, index) => index !== lastIndex));
    }
  };

  return (
    <div className="wrapper">
      <div>
        List: {list.length} total items.
        </div>
      <button onClick={handleAddItem}>Add</button>
      <button onClick={handleRemoveItem}>Remove</button>
      <ul>
        {list.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 the class component example.

References:

ReactJS

React - add / remove items from array in state (functional 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