//Here is my code
let otpTextInput = [];
const focusNext = (index, value) => {
if (index < otpTextInput.length - 1 && value) {
otpTextInput[index 1].focus();
}
if (index === otpTextInput.length - 1) {
otpTextInput[index].blur();
}
const text = otp;
otp[index] = value;
setOtp(otp);
if(index == 5){
checkOtp(otp,state.transactionId);
}
};
const focusPrevious = (key, index) => {
if (key === 'Backspace' && index !== 0) otpTextInput[index - 1].focus();
};
{[0, 1, 2, 3, 4, 5].map((item, index) => (
<TextInput
ref={textInputRef => (otpTextInput[index] = textInputRef)}
key={index}
autoFocus={index === 0}
onFocus={(e) => e.target.select}
style={styles.TextInputStyleClass}
placeholder="*"
maxLength={1}
numberOfLines={1}
keyboardType="numeric"
keyboardBehavior="extend"
placeholderTextColor={Colors.yellowAmber}
onChangeText={v => focusNext(index, v)}
onKeyPress={e => focusPrevious(e.nativeEvent.key, index)}
/>
))}
I have an array to create textinput multiple times for entering the otp values. Everything works fine in the textinput. But i am not able to clear textinput value. If user clicks submit button i want to clear all the textinput values.
CodePudding user response:
Have you tried adding the onSubmitEditing
prop and clearing the TextInput
there?
For example,
<TextInput
...
onSubmitEditing = {(e) => e.target.clear()}
/>
https://reactnative.dev/docs/textinput#onsubmitediting
CodePudding user response:
I think if you set value to your TextInput and change value of it will do
like this :
<TextInput
ref={textInputRef => (otpTextInput[index] = textInputRef)}
key={index}
autoFocus={index === 0}
value={otp[index]}
...
and in submit button call this kind of helper :
const clearInputs = ()=>{
setOtp(preOtp => preOtp.map(() => ''))
}
and do not set otp state in this way in focusNext function
otp[index] = value;
simply use prev like this :
setOtp(prevOtp => {
let temp = prevOtp
temp[index] = value
return temp
});