How to select the next TextInput after pressing the "next" keyboard button in react native?

sharmaprash

Prashant Sharma

Posted on November 21, 2024

How to select the next TextInput after pressing the "next" keyboard button in react native?

Steps:

  1. Use ref to Control Focus

    Assign a ref to each TextInput to programmatically control focus.

  2. Handle onSubmitEditing

    Use the onSubmitEditing event to focus the next input.

  3. Set returnKeyType

    Set returnKeyType to "next" for intermediate fields and "done" for the last one.

  4. Prevent Keyboard Dismissal

    Use blurOnSubmit={false} to keep the keyboard open while navigating.


Code Example:

import React, { useRef } from 'react';
import { TextInput, View, StyleSheet } from 'react-native';

const App = () => {
  const input1Ref = useRef(null);
  const input2Ref = useRef(null);
  const input3Ref = useRef(null);

  return (
    <View style={styles.container}>
      <TextInput
        ref={input1Ref}
        style={styles.input}
        placeholder="Input 1"
        returnKeyType="next"
        onSubmitEditing={() => input2Ref.current?.focus()}
        blurOnSubmit={false}
      />
      <TextInput
        ref={input2Ref}
        style={styles.input}
        placeholder="Input 2"
        returnKeyType="next"
        onSubmitEditing={() => input3Ref.current?.focus()}
        blurOnSubmit={false}
      />
      <TextInput
        ref={input3Ref}
        style={styles.input}
        placeholder="Input 3"
        returnKeyType="done"
        onSubmitEditing={() => console.log('Form submitted')}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', padding: 16 },
  input: { height: 50, borderColor: 'gray', borderWidth: 1, marginBottom: 10, paddingHorizontal: 10 },
});

export default App;
Enter fullscreen mode Exit fullscreen mode

Key Properties:

  1. ref: Links each TextInput to a reference for focus control.
  2. onSubmitEditing: Triggers focus on the next field when the "Next" button is pressed.
  3. returnKeyType: Sets the keyboard button type to "next" or "done".
  4. blurOnSubmit: Prevents the keyboard from closing when moving to the next input.
💖 💪 🙅 🚩
sharmaprash
Prashant Sharma

Posted on November 21, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related