How to Auto Focus on React Native TextInput?
Published On: 2024-02-17
Posted By: Harish

We have different ways to focus on the <TextInput> field. In this article, we will discuss a simple prop autoFocus to focus on the text input field.
This is useful to focus on the text input element on load, like in the login page or OTP screen where the first text input field will be in focus.
Create A New Project
Create a new react-native project by using npx. Check documentation for creating a new react native project.
npx react-native@latest init TextInputRN
Add TextInput Fields
Let's import TextInput from react and add three <TextInput> fields in the app.tsx file. This is to test the default focus behavior of text inputs.
Run the app.
#for Android
npx react-native run-android
#for ios
npx react-native run-ios
If we notice, there is no focus for the text input elements on load. Now add autoFocus prop withtrue as value to 2nd TextInput field.
//app.tsx
import {TextInput} from 'react-native';
...
<TextInput
  style={styles.input}
/>
<TextInput
  style={styles.input}
  autoCorrect={true}
/>
<TextInput
  style={styles.input}
/>
...
Now, you will see a keyboard with focus on the 2nd text input field. So, autoFocus prop creates a focus on the TextInput field on app or screen load (i.e, componentDidMount).
Default value of autoFocus prop is false. So if we don't mention the prop, <TextInput> shows default behavior of autoFocus={false}.
If we have autoFocus={true} prop to many TextInput's, the last TextInput field shows the focus.
<TextInput
  style={styles.input}
/>
<TextInput
  style={styles.input}
  autoCorrect={true}
/>
<TextInput
  style={styles.input}
  autoCorrect={true}
/>
In above inputs, 3rd TextInput will be on focus rather than 2nd one.

 Get Content Width and Height of React Native TextInput
Get Content Width and Height of React Native TextInput Using keyboardShouldPersistTaps Prop of ScrollView
Using keyboardShouldPersistTaps Prop of ScrollView Get Content Scroll Position Inside React Native TextInput
Get Content Scroll Position Inside React Native TextInput Press Events of React Native TextInput
Press Events of React Native TextInput ClearButtonMode in React Native TextInput
ClearButtonMode in React Native TextInput Custom Floating Label Text Input in React Native
Custom Floating Label Text Input in React Native