Hook for simplifying React Native TextInput Focus
Demo: tomfa.github.io/react-native-input-focus
OTP usage | Keyboard | App |
---|---|---|
![]() |
![]() |
![]() |
const { focus, setRef } = useInputFocus();
return (
<TextInput
ref={setRef("name")}
onSubmitEditing={() => focus("address")}
/>
<TextInput
ref={setRef("address")}
onSubmitEditing={() => focus("name")}
/>
)
- Hook: hooks.ts
- Example use: Inputs.tsx
<TextInput
keyboardType="phone-pad"
ref={setRef("one")}
maxLength={1}
onChangeText={(t) => t.length && focus("two")}
/>
<TextInput
keyboardType="phone-pad"
ref={setRef("two")}
maxLength={1}
onChangeText={(t) => t.length && focus("three")}
/>
<TextInput
keyboardType="phone-pad"
ref={setRef("three")}
maxLength={1}
onChangeText={(t) => t.length && focus("four")}
/>
<TextInput
keyboardType="phone-pad"
ref={setRef("four")}
maxLength={1}
onChangeText={(t) => t.length && focus("submit")}
/>
See gist for full working code.
For some keyboardTypes the phone will assume that returnKey intends a line shift, and the TextInput will not blur. This causes onSubmitEditing not to trigger.
In these cases, you can set blurOnSubmit
.
<TextInput
ref={setRef("email")}
keyboardType="ascii-capable"
blurOnSubmit={true}
onSubmitEditing={() => focus("phoneNumber")}
/>
This should not be done by default, as it can cause a glitchy keyboard UI on submit.
TextInput
has autoFocus
parameter, which activates on mount. In some cases, this won't trigger since the view is mounted in the background, before being visible. You can fix this with use of useEffect.
useEffect(() => focus("name"), []);
return (
<TextInput
ref={setRef("name")}
autoFocus {/* might not work */}
/>
)
For inputs such as phone numbers or credit cards, you might want to autofocus the next input once the input value becomes valid. To do this, simply call focus
whenever appropriate, from anywhere in the component.
<TextInput
ref={setRef("phoneNumber")}
onSubmitEditing={() => focus("email")}
maxLength={9}
onValueChange={txt => txt.length === 9 && focus("email")}
/>
<TextInput
ref={setRef("email")}
onSubmitEditing={() => focus("phoneNumber")}
/>
This keyboardType does not trigger onSubmitEditing. You'll have to rely on other mechanisms, such as onValueChange
.
<TextInput
ref={setRef("phoneNumber")}
keyboardType="phone-pad"
maxLength={9}
onValueChange={txt => txt.length === 9 && focus("email")}
/>
<TextInput
ref={setRef("email")}
onSubmitEditing={() => focus("phoneNumber")}
/>