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.
1import React from 'react';2import { View, Text, TextInput } from 'react-native';34class ReactNativeComponents extends React.Component {5 constructor(props){6 super(props);78 this.secondTextInput = React.createRef();9 }1011 render() {12 return (13 <View>14 <Text>React Components</Text>15 <TextInput16 placeholder="FirstTextInput"17 returnKeyType="next"18 onSubmitEditing={() => { this.secondTextInput.focus(); }}19 blurOnSubmit={false}20 />2122 <TextInput23 ref={(ref) => { this.secondTextInput = ref; }}24 placeholder="secondTextInput"25 />26 </View>27 );28 }29}3031export 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.
1import React, { useRef } from 'react';2import { View, Text, TextInput } from 'react-native';34export const ReactNativeComponents = () => {5 const secondTextInput = useRef();67 return (8 <View>9 <Text>React Components</Text>10 <TextInput11 placeholder="FirstTextInput"12 returnKeyType="next"13 onSubmitEditing={() => { secondTextInput.focus(); }}14 blurOnSubmit={false}15 />1617 <TextInput18 ref={secondTextInput}19 placeholder="secondTextInput"20 />21 </View>22 )23}
Thanks for reading…
Follow me on Twitter
Join our email list and get notified about new content
No worries, I respect your privacy and I will never abuse your email.
Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.