React-Native How to handle onPress from Item in flatlist ???

Daniel picture Daniel · Sep 5, 2018 · Viewed 12.7k times · Source

My FlatList is stateless component, and when item pressed I want to handle onPress by call method "handleOnPress". How can I do it ?? the below is sample codes.
`

handleOnPress = () => {
  .....
}
<SampleListView
    data={prop.data}
    onPress={this.handleOnPress}
/>
const SampleListView = (props: Props) => {
  return (
    <FlatList
        style={styles.container}
        data={props.data}
        keyExtractor={item => item.id.toString()}
        renderItem={renderItem}
    />
    )
}
renderItem = ({ item }: { item: DataSample }) => {
  return (
  <TouchableWithoutFeedback onPress={ () => props.onPress}>
      ....
  </TouchableWithoutFeedback>
  )
}

`

Answer

Tayfun Yaşar picture Tayfun Yaşar · Sep 5, 2018

Can you try this out?

handleOnPress = () => {
  .....
}
<SampleListView
    data={prop.data}
    onPress={this.handleOnPress}
/>
const SampleListView = (props: Props) => {
  return (
    <FlatList
        style={styles.container}
        data={props.data}
        keyExtractor={item => item.id.toString()}
        renderItem={renderItem}
    />
    )
}
renderItem = ({ item }: { item: DataSample }) => {
  return (
    <TouchableWithoutFeedback onPress={props.onPress}>
      <View>
        ....
      </View>
    </TouchableWithoutFeedback>
  )
}

Please pay attention to that 2 links.

https://facebook.github.io/react-native/docs/flatlist

TouchableWithoutFeedback with custom component inside doesn't fires onPress callback

The differences are, giving callback as param and adding View layer.