Home > OS >  React Native TouchableOpacity onPress works many times
React Native TouchableOpacity onPress works many times

Time:08-25

I have a ProductCard component which is inside of TouchableOpacity component, when click this component I want to navigate to another screen, everything works great, but when I click ProductCard component 2 or 3 times before react opens new screen, navigation works 2 or 3 times and instead of opening 1 screen, 2 or 3 screen opens, is there any way to handle this? This is my ProductCard component

<TouchableOpacity onPress={onPress} style={[styles.cardContainer, index % 2 === 0 ? { marginLeft: 15, marginRight: 8 } : { marginLeft: 8, marginRight: 15 }, style]}>
  <Image
    source={{
      uri: constants.IMAGE_START_URL   data.image,
    }}
    style={styles.cover}
  />
    <View style={styles.cardFooter}>
      <AppText style={styles.productPriceText}>{currencyFormat(data.price)}</AppText>
      <AppText style={styles.productAnnounceDateText}> 
      {data.announceDate}</AppText>
    </View>
    <IconButton onPress={() => favoriteHandle(data)} iconColor={isFavorite ? "red" : "#fff"} Icon={isFavorite ? icons.FavoriteIcon : icons.IconHeart}  style={styles.likeIcon}/>
</TouchableOpacity>

And FlatList for products

<FlatList
  style={generalStyles.container}
  numColumns={2}
  keyExtractor={(_, index) => index}
  data={favorites}
  renderItem={({item, index}) => <ProductCard favorites={favorites} 
  onPress={() => navigation.push("product_details", {
    title: item.propertyType   " "   currencyFormat(item.price),
    id: item.id
  })} 
  index={index} 
  data={item} 
  style={[ favorites.length % 2 === 1 && index === favorites.length - 1 && {marginRight: 28} ]}/>}
/>

CodePudding user response:

One thing is you can debounce your func, if you use lodash , you can use lodash debounce for it, so that when its pressed 2 or 3 times, it will only get invoked once.

const onNavPress = (item) => {
navigation.push("product_details", {
    title: item.propertyType   " "   currencyFormat(item.price),
    id: item.id
  })
}

<FlatList
  style={generalStyles.container}
  numColumns={2}
  keyExtractor={(_, index) => index}
  data={favorites}
  renderItem={({item, index}) => <ProductCard favorites={favorites} 
  onPress={lodash.debounce(() => onNavPress(item) ,1000)} //try this
  index={index} 
  data={item} 
  style={[ favorites.length % 2 === 1 && index === favorites.length - 1 && {marginRight: 28} ]}/>}
/>

Hope it helps. feel free for doubts

CodePudding user response:

Try to check, how do you import TouchableOpacity. Once i had a bug, when vscode imported it automatically from "react-native-gesture-handler" instead of "react-native", so i got different versions in same project.

  • Related