Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: FlatList index says is undefined

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

like image 983
Jacobo Avatar asked Sep 04 '26 03:09

Jacobo


2 Answers

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

like image 172
Tim Avatar answered Sep 05 '26 17:09

Tim


just wrap data, index with {} and change every data to item,

  renderItem={({item, index}) => ( ....
              ....
              key={item.item.id} // like this every where
like image 31
Jaydeep Galani Avatar answered Sep 05 '26 16:09

Jaydeep Galani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!