I like to increase the count of Item 1 without changing the count of Item 2 and Item 3. How do I do that in React Native? I am a beginner.
Here is my code: (Never mind the AppText and AppButton component those are my own)
const items = [
{ id: 1 },
{ id: 2 },
{ id: 3 }
]
const [quantity, setQuantity] = useState(1)
return (
<View style={styles.container}>
<FlatList
data={items}
renderItem={({ item }) => (
<View style={styles.item}>
<AppText style={styles.number}>Item {item.id} |</AppText>
<View style={styles.buttonContainer}>
<AppButton title={"-"} type={"contained"} style={styles.button} onPress={() => setQuantity(quantity - 1)} />
</View>
<AppText style={styles.number}>{quantity}</AppText>
<View style={styles.buttonContainer}>
<AppButton title={"+"} type={"contained"} style={styles.button} onPress={() => setQuantity(quantity + 1)} />
</View>
</View>
)}
/>
</View>
2
Answers
Need to create a useState object to map the values
items
object forquantity
andhandle that
items
state only (Don’t depend on other state if we can handle thedata
that passed toFlatList
).readability like don’t handle functions directly in
onPress
insteadcreate a separate function to handle that
Try below code