I am trying to create a dynamic input fields based on the object, the code below does create a dynamic form, HOWEVER, every time adding a character , keyboard will disappear and re-render ALL input fields again, and the character will show ,and it is impossible to type. I understand it is because the object has changed since I edited the object itself.
My tries: making a copy of the object and only edit the copy-object- but that specific input still re-render by itself and keyboard will disappear after one character is typed.
the renderTextInput function is working, I tried just by calling it without it being in a map and works great.
Question: how can i stop it from re-rendering when there is a new input ?
return{
<View>
{Object.keys(label).map( (key) => renderTextInput( key, key, label[key], (text) => setLabel((prevLabel) => ({ ...prevLabel,[key]: text}), 'default')))}
</View>
}
the function
const renderTextInput = (label, placeholder, value, onChangeText, keyboardType) => {
return (
<View key={value}>
<Text style={{ fontWeight: 'bold' }}>{placeholder}</Text>
<View style={ScannerStyle.shadow}>
<TextInput
style={ScannerStyle.input}
placeholder={placeholder}
placeholderTextColor="#aaaaaa"
value={value}
underlineColorAndroid="transparent"
autoCapitalize="none"
onChangeText={onChangeText}
keyboardType={keyboardType}
/>
</View>
</View>
);
};
example of label object
{
"Company Name": "Company Name",
"Address": "Address",
"City_State_ZipCode": "City_State_ZipCode",
"Country": "Country",
"Recvier Name": "Recvier Name",
"Recvier Street": "Recvier Street",
"Reciver City State ZipCode": "Reciver City State ZipCode",
"Reciver Country": "Reciver Country",
"Information": "Information"
}
2
Answers
It is all because an object in react does not guaranty the same order of data, it might randomly changed every time, and that was what I was facing. Once React detected there is a change of the order at layout layer, will re render the whole thing, to fix that just make a sort() for the object before rendering. then all inputs are generated by the same order and that fixed my issue.
you can check this solution Issue: React-Native – Keyboard closes on each keystroke for TextInput
it suggest you to keep a separate state for rendering text input and to store text change
and if you are doing it to minimize your code and textinput will remain static then you don’t need to use usestate hook for rending text input instead you can use a constant for rendering and a state to store response from text change