EN
React - delete element from state array
0 points
In this article, we would like to show you how to delete element from state array in React.
Quick solution:
xxxxxxxxxx
1
const [array, setArray] = React.useState(['a', 'b', 'c']);
2
3
// remove by index (item with index 1 will be removed)
4
setArray(array.filter((item, index) => index !== 1));
5
6
// remove by value (all 'b' items will be removed)
7
setArray(array.filter((item, index) => item !== 'b'));
In this example, we present how to delete an element from a state array (list
) using filter()
method and modifying the array's length
.
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([1, 2, 3]);
6
7
const handleRemove = () => {
8
const items = list;
9
if (items.length > 0) {
10
const lastIndex = items.length - 1;
11
setList(items.filter((item, index) => index !== lastIndex));
12
}
13
};
14
15
return (
16
<div className='wrapper'>
17
<div>List: {list.length} total items.</div>
18
<button onClick={handleRemove}>Remove item</button>
19
<ul>
20
{list.map((item, index) => (
21
<li key={index}>{item}</li>
22
))}
23
</ul>
24
</div>
25
);
26
};
27
28
const root = document.querySelector('#root');
29
ReactDOM.render(<App />, root);