TutorialsCourses

Focus on the Next TextInput when Next Keyboard Button is Pressed in React Native

Introduction

It's a common request to move from one text input to another when that field is submitted. There are many ways to slice it up and obscure what is happening in some form helper libraries, but lets look at how to accomplish this.

The Issue

We have 2 fields. When we press Next on our First Name input we want to move to the Last Name input.

<TextInput
    placeholder="First Name"
/>

<TextInput
    placeholder="Last Name"
/>

The Solution

The first step is getting a ref to our Last Name input. The one we want to focus on after our first input is submitted. We do that with the useRef hook and pass that to the ref prop of our second TextInput.

const lastNameRef = useRef();

<TextInput placeholder="Last Name" ref={lastNameRef} />;

Then we need to add 3 props to our first input returnKeyType, onSubmitEditing, and blurOnSubmit set to false.

<TextInput
  placeholder="First Name"
  returnKeyType="next"
  onSubmitEditing={() => {
    lastNameRef.current.focus();
  }}
  blurOnSubmit={false}
/>

All together

const lastNameRef = useRef();

// Your other code
<TextInput
  placeholder="First Name"
  returnKeyType="next"
  onSubmitEditing={() => {
    lastNameRef.current.focus();
  }}
  blurOnSubmit={false}
/>
<TextInput placeholder="Last Name" ref={lastNameRef} onSubmitEditing={() => {
    // Execute code to update users name
}}/>;

The returnKeyType is for display purposes. It will show Next to your users where the submit button would be. Indicating that there is another field to move to that they need to fill out. The onSubmitEditing is called when that button is pressed. This will then trigger focus on the text input that we have a ref to.

Finally blurOnSubmit set to false will prevent the keyboard from flashing when transitioning between text inputs. When we trigger focus on a second input this causes a blur to fire on our First Name text input. This would cause the keyboard to dismiss as there is no currently active field that needs typing in. Then when our Last Name input gets focused it would cause the keyboard to reappear. So to prevent this interaction we are basically telling the system to leave the keyboard up when we submit because we know we're moving on to another input. On the LastName input once submitted we do want to blur the field and hide the keyboard.