React Native List with Map Method
What I want to achieve,
I want when click item then a new Item (I preferer add a new custom View) is added below the Selected item.
Expo Snack code>
https://snack.expo.dev/@stefanosalexandrou/tenacious-french-fries
2
Answers
There are some points to consider and I’ll list them here, before providing an idea of a solution:
<FlatList />
/<SectionList />
. Use those components instead of.map()
for rendering component listskey
prop when rendering a list of components using.map()
or other Array methodsWith minimal changes to your provided code, you can create a state to store the list and when the item is pressed you can insert a new item inside this list:
Sandbox with working code: https://snack.expo.dev/5rvTbrEvO
Since you are changing the background of the selected item, it is necessary that you update the ID’s of every item in the list, for otherwise inserting elements will break this functionality. Furthermore, you need to add a state for for otherwise you cannot trigger a UI change
You could implement the desired behaviour as follows.
Use
slice
in order to split the array into two parts. Usemap
for updating theid
attribute of the elements in the second array. Finally, combine both parts but insert a new element between them.Here is an updated snack.