I'm trying to retrieve the index of the clicked element on a FlatList in react native. As the documentation says, I'm passing an index to the renderItem prop. My code is the following:
/**
* Goes to the show view of a container
* @param {*} index
*/
showContainer = (index) => {
console.log(index);
}
render() {
return (
<DefaultScrollView style={styles.container}>
<FlatList
data={this.props.containers}
renderItem={(data, index) => (
<ListItem
containerStyle={{borderBottomWidth: 1, borderBottomColor: "#000"}}
key={data.item.id}
leftAvatar={Image}
onPress={() => {this.showContainer(index)}}
rightIcon={{ name: "ios-eye", type: "ionicon" }}
subtitle={
`${data.item.dummy === true? 'Por favor configura tu dispositivo' : 'Contenido actual: '}`
}
subtitleStyle={(data.item.dummy == true)? [styles.configurationText, styles.subtitule] : styles.subtitule}
title={data.item.name}
titleStyle={styles.title}
/>
)}/>
</DefaultScrollView>
);
}
The only way it worked is if I pass a number as an index, for example:
renderItem={(data, index = 0), but how can I pass the index variable to always have the correct index?
Thanks in advance
You need to destructure your data, before passing it to renderItem.
So change:
renderItem={(data, index) => ( ...
To:
renderItem={({item, index}) => (...
And then you can access your data with item.id for example.
Simplified working demo:
https://snack.expo.io/B1AONkehN
just wrap data, index with {} and change every data to item,
renderItem={({item, index}) => ( ....
....
key={item.item.id} // like this every where
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With