Change the focus automatically to the next TextInput in react native
The answered question was definitely beneficial but my es-lint
was throwing an error saying use of strings or maybe this.refs is depreciated
So this is what I did, create refs in the constructor (probably this is how react suggests). In my cases, I wanted 4 Text Inputs boxes
constructor(props) {
super(props)
this.keyboardHeight = new Animated.Value(0)
this.num1 = React.createRef()
this.num2 = React.createRef()
this.num3 = React.createRef()
this.num4 = React.createRef()
}
And then render component like this
<View style={styles.inputBoxes}>
<TextInput
ref={this.num1}
style={styles.textInput}
onChangeText={number => this.inputNumber(number, 1)}
value={this.state.num1}
keyboardType="numeric"
numberOfLines={1}
/>
<TextInput
ref={this.num2}
style={styles.textInput}
onChangeText={number => this.inputNumber(number, 2)}
value={this.state.num2}
keyboardType="numeric"
numberOfLines={1}
/>
<TextInput
ref={this.num3}
style={styles.textInput}
onChangeText={number => this.inputNumber(number, 3)}
value={this.state.num3}
keyboardType="numeric"
numberOfLines={1}
/>
<TextInput
ref={this.num4}
style={styles.textInput}
onChangeText={number => this.inputNumber(number, 4)}
value={this.state.num4}
keyboardType="numeric"
numberOfLines={1}
/>
</View>
notice the refs here inside TextInput. In my onChange, I am passing a flag, telling which button it is to this.inputNumber
And this is how my inputNumber
function looks like
inputNumber(value, flag) {
const completeFlag = `num${flag}`
this.setState({[completeFlag]: value})
flag = flag + 1
if (flag < 5 && value) {
const nextFlag = `num${flag}`
const textInputToFocus = this[nextFlag]
textInputToFocus.current.focus()
}
}
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
}}
/>