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:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
const App = () => {
const [list, setList] = React.useState([]);
const handleAdd = () => {
const items = list;
setList([...items, `item-${items.length}`]);
};
const handleRemove = () => {
const items = list;
if (items.length > 0) {
const lastIndex = items.length - 1;
setList(items.filter((item, index) => index !== lastIndex));
}
};
return (
<div>
<div>List: {list.length} total items.</div>
<button onClick={handleAdd}>Add</button>
<button onClick={handleRemove}>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.