How to select the next TextInput after pressing the “next” keyboard button with React Native?

Sometimes, we want to select the next TextInput after pressing the “next” keyboard button with React Native.

In this article, we’ll look at how to select the next TextInput after pressing the “next” keyboard button with React Native.

How to select the next TextInput after pressing the “next” keyboard button with React Native?

To select the next TextInput after pressing the “next” keyboard button with React Native, we can assign refs to the TextInputs we want to set focus on.

And then we call focus on the ref.current of the TextInput to set focus on the input.

For instance, we write:

import * as React from 'react';
import { View, StyleSheet } from 'react-native';
import { TextInput } from 'react-native-paper';

const MyComponent = () => {
  const refInput2 = React.useRef();
  const refInput3 = React.useRef();

  return (
    <View>
      <TextInput
        placeholder="Input1"
        autoFocus={true}
        returnKeyType="next"
        onSubmitEditing={() => refInput2.current.focus()}
      />
      <TextInput
        placeholder="Input2"
        returnKeyType="next"
        onSubmitEditing={() => refInput3.current.focus()}
        ref={refInput2}
      />
      <TextInput placeholder="Input3" ref={refInput3} />
    </View>
  );
};

export default MyComponent;

to create 2 refs with useRef.

Then we set the ref prop of the 2nd and 3rd inputs.

Next, we set onSubmitEditing prop of the first 2 inputs to functions that calls focus on the inputs to put focus on them.

Therefore, when we press enter on the first input, focus is moved to the 2nd one.

And when we press enter on the 2nd input, focus is moved to the 3rd one.

Conclusion

To select the next TextInput after pressing the “next” keyboard button with React Native, we can assign refs to the TextInputs we want to set focus on.

And then we call focus on the ref.current of the TextInput to set focus on the input.