Languages
[Edit]
EN

React - array as state

3 points
Created by:
nickkk0
647

In this article, we would like to show you how to use array as a state in React and later render some elements based on the array. 

The most common problem when react beginners try to use arrays are:

  • missing unique key property for each array item,
  • how to modify array and refresh component state after modification.

In this article we would like to show 4 basics operations on arrays:

  1. elements rendering based on array items,
  2. items adding,
  3. items deleting,
  4. items modifying.

Check below section to see how it works.

Note: below solutions are summary of the most commonly used practices.

1. Elements rendering based on array items example

Edit

It is very important to add for each children key property - that helps React to detect DOM changes in an optimal way. To iterate over array we can use built-in JavaScript map() function.

2. Items adding into array example

Edit

To notify React about state change we need to pass to state always different reference than the current one. That situation makes we can add item into array with [...list, newItem] operation that returns new object with the same items).

Remember: by using list.push() method we will not see any component change because reference stored as state will be not changed - component is re-rendered only on reference or value change in state.

3. Items deleting from array example

Edit

One of the most simple way how to remove element from array and make copy of them is to use filter() method.

4. Items modifying in array example

Edit

Using map() method we are able to transform array into a new one. So this way we are able to change only desired items.

 

See also

Edit
  1. React - useArray() custom hook example 
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 - array as state
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