Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click listener in flatlist

Tags:

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> } 
like image 257
Amrita Stha Avatar asked Jun 17 '17 19:06

Amrita Stha


People also ask

What is extraData in FlatList?

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.

What is keyExtractor in FlatList?

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.

Does FlatList have onPress?

Each item of FlatList does support onPress functionality.


1 Answers

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); } 
like image 106
Manish Ahire Avatar answered Oct 04 '22 09:10

Manish Ahire