EN
React - how to add / remove items from array in state (functional component)
6 points
In this article, we would like to show you how to add and remove items from an array used as a 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] = ...
).
The below example provides two actions:
- Add item: that calls
handleAdd
method that uses a spread operator (...
) to create an array copy with a new item that is put on the last position and finallysetList()
method updates the state value - we set a new reference as a state. - Remove item: that calls
handleRemove
method that usesfilter()
method to make array copy with the removed indicated item (in example case it is the last index) - we set new reference as a state.
Runnable example:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
4
const App = () => {
5
const [list, setList] = React.useState([]);
6
7
const handleAdd = () => {
8
const items = list;
9
setList([items, `item-${items.length}`]);
10
};
11
12
const handleRemove = () => {
13
const items = list;
14
if (items.length > 0) {
15
const lastIndex = items.length - 1;
16
setList(items.filter((item, index) => index !== lastIndex));
17
}
18
};
19
20
return (
21
<div>
22
<div>List: {list.length} total items.</div>
23
<button onClick={handleAdd}>Add</button>
24
<button onClick={handleRemove}>Remove</button>
25
<ul>
26
{list.map((item, index) => (
27
<li key={index}>{item}</li>
28
))}
29
</ul>
30
</div>
31
);
32
};
33
34
const root = document.querySelector('#root');
35
ReactDOM.render(<App />, root);
Note:
Go to this article to see the class component example.