0

I'm wanting to access the index of a thats being generated from with dataArray. For example:

<List dataArray={this.props.groceries} renderRow={(groceryListItem, index) =>
    <ListItem>  
        <Text>{index}</Text>
    </ListItem>
    }
>
</List>

However, this does not work. How can I access this dynamic index? Thanks!

awebdev
  • 997
  • 2
  • 10
  • 27

3 Answers3

3

What is List is it ListView? İf it is you can get the index 3. prop

<ListView 
renderRow={(rowData, sectionID, index) => // you can get the index from 3.
...
Yasin Ugurlu
  • 691
  • 5
  • 11
0

React Native FlatList has similar structure to your List component and it's highly recommended by react native community to use FlatList because of efficiency, index of rendered item is accessible easily. here is an simple usage for what you want:

render() {
  return (
    <FlatList
      data={[
        {title: "title1"},
        {title: "title2"},
        {title: "title3"},
        {title: "title4"},
        {title: "title5"},
        {title: "title6"},
        {title: "title7"},
        {title: "title8"},
      ]}
      renderItem={(item) => <Text>{item.index}</Text>}
      keyExtractor={(item, index) => index.toString()}/>
  );
}

item parameter in renderItem has two important property.

  1. index: index of item being rendered
  2. data: the data you provided to flat list, in this sample is one of objects of array passed to data props of flatList, e.g. {title: "title1"} that I don't use this data in renderItem method. you can do what you want with it in your way like this: data={this.props.groceries}
Saeed Zhiany
  • 2,051
  • 9
  • 30
  • 41
0

I am using following:

<List dataArray={this.props.groceries} renderItem={({item, index}) =>
    <ListItem key={index}>  
        <Text>{item}</Text>
    </ListItem>
    }
>
</List>
Khurshid Ansari
  • 4,638
  • 2
  • 33
  • 52