How can I add a iterable index to my flatlist? In my SummaryCard
component, I need to fire a function that tracks which SummaryCard
is clicked, for example, "Summary Card vehicle 1 clicked", "summary vehicle 2 clicked".
<FlatList
data={data}
contentContainerStyle={styles.list}
renderItem={({ item }) => (
<SummaryCard vehicle={item} key={item.vehicleId} />
)}
keyExtractor={(item) => item.vehicleId.toString()}
ItemSeparatorComponent={() => <View style={styles.separator} />}
/>
4
Answers
The data can be modified to have an index property. You can do this just after receiving the data.
Then you can modify your Flatlist component to use the modified data and can access the card number by
item.index
.renderItem takes an object with three possible properties:
item
(Object): The item fromdata
being rendered.index
(number): The index corresponding to this item in thedata
array.separators
(Object)highlight
(Function)unhighlight
(Function)updateProps
(Function)select
(enum(‘leading’, ‘trailing’))newProps
(Object)So you could write some code like this
The second argument from
renderItem
is the index of the data passed to the FlatList.You simply need to do:
It is possible to use the
index
argument inside therenderItem
callback function.But indexes can eventually change if the list changes the size or content. As a solution to that you could consider tracking your clicked elements by
id
instead (orvehicleId
). You can create some logic like this: