Reputation: 73
I want to increment the value and set it to TextInput onclick. But there are many TextInputs and buttons, created dynamically with each item in FlatList.
<FlatList keyExtractor={(item, index) => item.id.toString()} data={allGroceryItems} renderItem={itemData => (
<View style={{ alignItems: 'center', }}>
//id in item.id is an object in array & addQty(id) is just an empty function for now
<TouchableOpacity style={styles.btnCount} onPress={() => addQty(itemData.item.id)}>
<Text style={{fontFamily: 'open-sans-reg', fontSize: 16}}>+</Text>
</TouchableOpacity>
<TextInput keyboardType="numeric" placeholder="0" style={styles.txtCount}/> // this is the TextInput
<TouchableOpacity style={styles.btnCount} onPress={() => deleteQty(itemData.item.id)}>
<Text style={{fontFamily: 'open-sans-reg', fontSize: 22}}>-</Text>
</TouchableOpacity>
</View>
)}
/>
So, basically its a counter. When +
button is pressed, it increments the number and set to the clicked index's TextInput value. When -
button is pressed, it decrements the number and set to the clicked index's TextInput value.
How to get the clicked button's TextInput and set the value of it?
Upvotes: 1
Views: 443
Reputation: 73
I finally figured it out by adding a hook state.
Solution:
const [txtValue, setTxtValue] = useState([]);
const addQty = (id) => {
const dataArr = [...txtValue];
var prev = `${dataArr[id]}` == 'undefined' ? 0 : dataArr[id];
dataArr[id] = prev + 1;
setTxtValue(dataArr);
}
const deleteQty = (id) => {
const dataArr = [...txtValue];
var prev = `${dataArr[id]}` == 'undefined' ? 0 : dataArr[id];
if(prev == 0){
dataArr[id] = prev;
}else{
dataArr[id] = prev - 1;
}
setTxtValue(dataArr);
}
<FlatList keyExtractor={(item, index) => item.id.toString()} data={allGroceryItems} renderItem={itemData => (
<View style={{ alignItems: 'center', }}>//id in item.id is an object in array
<TouchableOpacity style={styles.btnCount} onPress={() => addQty(itemData.item.id)}>
<Text style={{fontFamily: 'open-sans-reg', fontSize: 16}}>+</Text>
</TouchableOpacity>
<TextInput value={`${txtValue[itemData.item.id]}`=== "undefined" ? '0' : `${txtValue[itemData.item.id]}`} keyboardType="numeric" placeholder="0" style={styles.txtCount}/> // this is the TextInput
<TouchableOpacity style={styles.btnCount} onPress={() => deleteQty(itemData.item.id)}>
<Text style={{fontFamily: 'open-sans-reg', fontSize: 22}}>-</Text>
</TouchableOpacity>
</View>
)}
/>
Upvotes: 1