Search code examples
react-nativeonpress

get product id set in const use onPress in react native loop


I want to add key={item.id} value in pid use onPress, and her data come to data base use loop in react native

const addToWishlist = () => {
     const [pid, setPid] = useState('');
}
return (
  <>
   {ProductData.map((item, index) => {
     return (
       <View key={index} style={styles.prod}>
         <TouchableOpacity onPress={addToWishlist} key={item.id}>
           <Feather name="heart" color={heartColor} style={{fontSize:16}}/>
         </TouchableOpacity>
       </View>
     )
   })}
  </>
)

Solution

  • Your function should accept an arg id and you must send it when the onPress is triggered.

    onPress={() => addToWishlist(item.id)}

    const addToWishlist = (id) => {
      console.log(id)
      // const [pid, setPid] = useState('');
      // You should not declare a hook in a function
    }
    
    return (
      <>
       {ProductData.map((item, index) => (
         <View key={index} style={styles.prod}>
           <TouchableOpacity onPress={() => addToWishlist(item.id)} key={item.id}>
             <Feather name="heart" color={heartColor} style={{fontSize:16}}/>
           </TouchableOpacity>
         </View>
       )})
     </>
    )