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> }
The extraData prop is used to re-render the FlatList items dynamically. So what we are doing is that we make 2 Array in our tutorial and render the FlatList using first array object. We would also make 1 button.
keyExtractor Used to extract a unique key for a given item at the specified index. Key is used for caching and as the react key to track item re-ordering. The default extractor checks item. key , then item.id , and then falls back to using the index, like React does.
Each item of FlatList does support onPress functionality.
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); }
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