Reputation: 1008
I am trying to edit the value of the dynamically generated TextIput fields value.
Here is my JSON array
{
"measurements": [{
"id": 200,
"sub_type_id": 34,
"sub_type": "TOPS SL",
"measurement_input": "15"
}, {
"id": 201,
"sub_type_id": 47,
"sub_type": "TOPS ABOVE CHEST",
"measurement_input": "40"
}, {
"id": 202,
"sub_type_id": 48,
"sub_type": "TOPS CHEST",
"measurement_input": "42"
}]
}
base on the above JSON array data I have created TextInputs dynamically but the problem is I am not able to edit the TextInputs values.
Code for creating TextInput
....
this.state = {
...
subtypes: props.route.params.editdata.measurements,
inputData: [],
...
}
...
{this.state.subtypes.map((inputs, idx) => {
return (
<View style={{flex: 1, padding: 2, margin: 10}}>
<Text style={{margin: 2}}>{inputs.sub_type}</Text>
<View
style={{
flex: 1,
flexDirection: 'row',
alignItems: 'center',
}}>
<View style={{flex: 1}}>
<TextInput
style={styles.textInput}
placeholder={inputs.sub_type}
value={inputs.measurement_input} //<------ value not able to change
onChangeText={(text) =>
this.addValues(text, idx, inputs.sub_type_id)
}
/>
</View>
</View>
</View>
);
})}
This is the function for taking value from TextInput.
//------ HERE I am not able to do editable parts --------
addValues = (text, index, id) => {
let dataArray = this.state.inputData;
let checkBool = false;
if (dataArray.length !== 0) {
dataArray.forEach((element) => {
if (element.index === index) {
element.measurement_input = text;
element.sub_type_id = id;
checkBool = true;
}
});
}
if (checkBool) {
this.setState({
inputData: dataArray,
});
} else {
dataArray.push({measurement_input: text, index: index, sub_type_id: id});
this.setState({
inputData: dataArray,
});
}
};
I tried many technics but not able to perform the value editable.
Upvotes: 1
Views: 972
Reputation: 1008
I fixed it using only two lines of code.
it doesn't need to copy the updated values in another array (inputData
state array). Just only update to the same array (subtypes
state array that contains my actual edited json data) and I used this.forceUpdate();
javascript function.
Here is the updated code, all the updated values will contain in the this.state.subtypes
.
{this.state.subtypes.map((inputs, idx) => {
return (
<View style={{flex: 1, padding: 2, margin: 10}}>
<Text style={{margin: 2}}>{inputs.sub_type}</Text>
<View
style={{
flex: 1,
flexDirection: 'row',
alignItems: 'center',
}}>
<View style={{flex: 1}}>
<TextInput
style={styles.textInput}
placeholder={inputs.sub_type}
value={inputs.measurement_input}
onChangeText={(text) =>
{
//this.addValues(text, idx,inputs.sub_type_id, inputs.measurement_input) //<----- no need
// these two line of codes work out
this.state.subtypes[idx].measurement_input = text
this.forceUpdate();
}
}
/>
</View>
</View>
</View>
);
})}
Upvotes: 1
Reputation: 31
Why are you using this.state.subtypes to render and set state on inputData?
Upvotes: 0