Reputation: 13
Sorry guys i'am still learning react native and i want update value of each qty(quantity) item from input, so i have this state,
this.state={
selectedObject={
otherAttributes:'',
items:[
{name:'a',qty:''},
{name:'b',qty:''},
],
},
}
then i have this function to render the TextInput,
renderPage(){
return this.state.selectedObject.items.map(item ,i)=>
<View style={{margin:15}}>
<Text>Name: {item.name}</Text>
<TextInput style={styles.input} keyboardType='numeric' maxLength={10}
value={?}
onChangeText={?}
}}/>
</View>
)
}
and i dont know what to do inside the value and onchangeText,
This is what i tried, in the TextInput
renderPage(){
const itemqty = this.state.selectedObject.items;
return itemqty.map((item,i)=>
<View style={{margin:15}}>
<Text>Name: {item.name}</Text>
<TextInput style={styles.input} keyboardType='numeric'
value={itemqty[i].qty}
onChangeText={(qty)=>{
this.setState({items[i].qty: qty});
}}/>
</View>
)
}
after trying this i'am aware that value can't have '[i]' aswell as in the setState. Because i was trying so that the value qty will go to the respected items qty as well when setState it.
So what i expect is i can change the value of the quantity of the items from the input that are available in this case there are 2, but later on it can be 3,4,5,6 items with qty in each one and set it to the respected state.
Thank you
Upvotes: 1
Views: 57
Reputation: 1365
You have to pass the modified state properties to setState.
PS: I had to update in order to reflect Junius L. comment about not changing component state.
renderPage(){
const itemqty = this.state.selectedObject.items;
return itemqty.map((item,i)=>
<View style={{margin:15}}>
<Text>Name: {item.name}</Text>
<TextInput style={styles.input} keyboardType='numeric'
value={item.qty}
onChangeText={(qty)=>{
let newSelectedObject = {...this.state.selectedObject};
newSelectedObject.items = [...newSelectedObject.items];
newSelectedObject.items[i] = {...newSelectedObject.items[i], qty};
this.setState({selectedObject: newSelectedObject});
}}/>
</View>
)
}
Also, selectedObject is a state property. So the correct is
this.state={
selectedObject:{
otherAttributes:'',
items:[
{name:'a',qty:''},
{name:'b',qty:''},
],
},
}
Upvotes: 1
Reputation: 16122
Try to avoid state mutation, by not updating the array directly.
hanldeChange = (value, index) => {
const items = [
...this.state.selectedObject.items.slice(0, index),
Object.assign({}, this.state.selectedObject.items[index], { qty: value }),
...this.state.selectedObject.items.slice(index + 1),
];
this.setState(prevState => ({
selectedObject: {
...prevState.selectedObject,
items: items,
},
}));
};
In your input do
<TextInput
style={styles.input}
keyboardType="numeric"
value={this.state.selectedObject.items[i].qty}
onChangeText={qty => this.hanldeChange(qty, i)}
/>
Upvotes: 0