Click listener in flatlist

Amrita Stha picture Amrita Stha · Jun 17, 2017 · Viewed 32.5k times · Source

How can I add click listener in Flatlist?

My code:

renderItem({item, index}){
    return <View style = {{
    flex:1,
    margin: 5, 
    minWidth: 170, 
    maxWidth: 223,
    height: 304,
    maxHeight: 304,
    backgroundColor: '#ccc',
    }}/>
}
render(){
return(<FlatList
contentContainerStyle={styles.list}
data={[{key: 'a'}, {key: 'b'},{key:'c'}]}
renderItem={this.renderItem}
/>);
}
}

Update 1: I used button but it is not working in Flatlist. However using only button instead of Flatlist, it works. Why is it not working in Flatlist renderItem?

_listener = () => {
    alert("clicked");
}

renderItem({item, index}){
    return<View>
      <Button
          title = "Button"
          color = "#ccc"
          onPress={this._listener}
      />
    </View>
}

Answer

Manish Ahire picture Manish Ahire · Jul 31, 2018

I used TouchableWithoutFeedback. For that, you need to add all the renderItem elements (i.e your row) into the TouchableWithoutFeedback. Then add the onPress event and pass the FaltList item to the onPress event.

import {View, FlatList, Text, TouchableWithoutFeedback} from 'react-native';

render() {

  return (

      <FlatList style={styles.list}

          data={this.state.data}

          renderItem={({item}) => (

              <TouchableWithoutFeedback onPress={ () => this.actionOnRow(item)}>

                  <View>
                     <Text>ID: {item.id}</Text>
                     <Text>Title: {item.title}</Text>
                  </View>

             </TouchableWithoutFeedback>

         )}
      /> 
   );
}

actionOnRow(item) {
   console.log('Selected Item :',item);
}