Hello Friends 👋,

Welcome To Infinitbility! ❤️

This tutorial will help you to manage textinput focus programmatically in react native, here you will get an example of how we control text input auto-selection using code, we can auto show selected or focus input or whenever we can change user focus to another textinput.

Let’s start today topic How to focus textinput in react native

React Native textinput provide the option to blur and focus any textinput but for use those function we have to create ref for it.

First understand how can we create ref of any textinput in react native then we will go on the second step for control focus and blur of textinput.

focus textinput in class component example

For creating ref first we have to define those refs on the constructor.

this.firstTextInput = React.createRef();

let’s understand with the example of create ref of textinput in class component.

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

class ReactNativeComponents extends React.Component {
    constructor(props){
        super(props);

        this.secondTextInput = React.createRef();
    }

    render() {
        return (
            <View>
                <Text>React Components</Text>
                <TextInput
                    placeholder="FirstTextInput"
                    returnKeyType="next"
                    onSubmitEditing={() => { this.secondTextInput.focus(); }}
                    blurOnSubmit={false}
                />

                <TextInput
                    ref={(ref) => { this.secondTextInput = ref; }}
                    placeholder="secondTextInput"
                />
            </View>
        );
    }
}

export default ReactNativeComponents;

The above example also added auto navigate the second textinput when the first input fired submit an event.

focus textinput in functional component example

In functional component, React provide useRef() functionality, and we can use for creating ref of textinput.

let’s understand the same example in the functional component.

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

export const ReactNativeComponents = () => {
    const secondTextInput = useRef();

    return (
        <View>
            <Text>React Components</Text>
            <TextInput
                placeholder="FirstTextInput"
                returnKeyType="next"
                onSubmitEditing={() => { secondTextInput.focus(); }}
                blurOnSubmit={false}
            />

            <TextInput
                ref={secondTextInput}
                placeholder="secondTextInput"
            />
        </View>
    )
}

Thanks for reading…