Reputation: 2381
How can I set focus to an Input in react native?
I have some inputs in my code:
<Input
value={CompName}
onChangeText={(text) => this.onChangeText(text, 'CompName')}
style={styles.valueText}
/>
<Input
value={Phone}
onChangeText={(text) => this.onChangeText(text, 'Phone')}
style={styles.valueText}
/>
...
And I validate if it is empty. IF empty, I set a Alert message and I would like to focus on the field. How can I do it?
myFunc = () => {
if(CompName === '' || CompName === undefined){
Alert.alert('Company Name is required.');
// set focus here??
return;
}
...
}
Thanks
Upvotes: 1
Views: 681
Reputation: 3610
firstly, in react-native, it is TextInput
. and here is two methods exposed via the native element. they are .focus() and .blur() that will focus or blur the TextInput programmatically.
for use it, you have to set a ref for the TextInput
.
<TextInput
value={this.state.compName}
onChangeText={(text) => this.onChangeText(text, 'CompName')}
style={styles.valueText}
ref={(input) => { this.compNameInput = input; }}
/>
myFunc = () => {
if(this.state.compName === '' || this.state.comNam === undefined){
Alert.alert('Company Name is required.');
// set focus here??
this.compNameInput.focus();
return;
}
...
}
I suggest use the state for the compName
, like this.state.compName
Upvotes: 1