Languages
[Edit]
EN

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

6 points
Created by:
Zayyan-Todd
860

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 finally setList() method updates the state value - we set a new reference as a state.
  • Remove item: that calls handleRemove method that uses filter() 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:

Note:

Go to this article to see the class component example.

References:

Edit
1
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 (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