In this lesson, you will learn how to direct a user's attention through your app by programmatically controlling which input field has the "focus" (the state where the keyboard is open and ready for typing).
Understanding Focus
When a user taps an input field, the system grants it "focus," which triggers the keyboard to appear. However, in a professional user flow, you often want to guide the user automatically. For example, if a user finishes typing their "First Name," you might want to automatically jump them to the "Last Name" field without requiring an extra tap.
To achieve this in React Native, we use a ref (reference) to interact with a component instance directly.
The Implementation Pattern
First, you create a reference using the useRef hook. Then, you attach that reference to your TextInput component. Finally, when you are ready to shift the focus, you call the .focus() method on that reference.
import React, { useRef } from 'react';
import { TextInput, Button, View } from 'react-native';
const MyForm = () => {
const passwordInputRef = useRef(null);
return (
<View>
<TextInput
placeholder="Username"
returnKeyType="next"
onSubmitEditing={() => passwordInputRef.current.focus()}
/>
<TextInput
ref={passwordInputRef}
placeholder="Password"
secureTextEntry
/>
</View>
);
};
In this example, the onSubmitEditing prop is a built-in event that fires when the user hits the "Enter" or "Next" button on their virtual keyboard. By calling passwordInputRef.current.focus(), we immediately shift the input cursor and the keyboard to the second field.
Managing User Flow
Controlling focus is not just about convenience; it is about reducing friction. By automating the transition between inputs, you keep the user in a "flow state" where they can complete forms quickly. You can also use blur() to remove focus, which hides the keyboard—a useful trick to implement when a user taps away from an input or submits a form, helping your interface feel clean and responsive.
Key Takeaway: Programmatically managing focus via refs allows you to guide the user’s journey through your interface, making forms feel intuitive rather than manual.