I am developing an App with react native. I have three TextInput boxes as bellow:
I need to change the focus of the TextInput box automatically, if the user inserts a number. Then, as soon as he/she inserts the last number a function should be executed.
Here is my code:
<View style={styles.squareContainer}>
<View style={styles.square}>
<TextInput
onChangeText={(oldPassword) => this.setState({oldPassword})}
style={{flex:1}}
ref="1"
keyboardType={'numeric'}
style={styles.inputText}
maxLength = {1}
underlineColorAndroid='rgba(0,0,0,0)'
numberOfLines={1}
secureTextEntry={true}
onSubmitEditing={() => this.focusNextField('2')}
/>
</View>
<View style={styles.square}>
<TextInput
style={{flex:1}}
ref="2"
onChangeText={(oldPassword) => this.setState({oldPassword})}
keyboardType={'numeric'}
maxLength = {1}
style={styles.inputText}
underlineColorAndroid='rgba(0,0,0,0)'
numberOfLines={1}
secureTextEntry={true}
onSubmitEditing={this.maxLength?1:() => this.focusNextField('3')}
/>
</View>
<View style={styles.square}>
<TextInput
style={{flex:1}}
ref="3"
onChangeText={(oldPassword) => this.setState({oldPassword})}
returnKeyType='next'
keyboardType={'numeric'}
style={styles.inputText}
underlineColorAndroid='rgba(0,0,0,0)'
numberOfLines={1}
secureTextEntry={true}
/>
</View>
</View>
In other words, for example if a user wants to insert 153, he/she should insert 1 into the first TextInput, then the curser and focus should replace to the next TextInput automatically and she/he can inserts 5 and finally by moving the focus and curser to the third TextInput, he/she can inserts 3. As soon as he inserts 3, I need to execute this.triggerFunction()
.
I tried to use the following trick as you can see, but it did't work:
onSubmitEditing={this.maxLength?1:() => this.focusNextField('3')}
Can you help me to solve this problem. Thanks in advance.
You have to focus the TextInput
you want the cursor to go to. To do that, You can set maxLength
to 1
, and call onChangeText
to change focus.
You may also want to capture the value
and store it in state.
Another thing you should is to use words or characters for your references. These are going to be called as objects and numbers may be a bit confusing to call. i.e ref={'input_1'}
instead of ref={'1'}
<TextInput
style={{flex:1}}
ref="input_1"
keyboardType={'numeric'}
style={styles.inputText}
maxLength = {1}
value={this.state.value}
underlineColorAndroid='rgba(0,0,0,0)'
numberOfLines={1}
secureTextEntry={true}
onChangeText={value => {
this.setState({ value })
if (value) this.refs.input_2.focus(); //assumption is TextInput ref is input_2
}}
/>