Last Updated on December 10, 2020.
TextInput is one of the most important components in React Native. In this blog post, I am sharing with you how to make the TextInput focus automatically. When the TextInput is in focus the keyboard appears automatically and this prompts the user to type in.
You can use autoFocus prop to make the textInput on focus in react native. When the autoFocus is made true the input get focused on componentDidMount lifecycle. The default value of autoFocus is false.
Following is a react native example which uses autoFocus prop.
Class based component
import React, {Component} from 'react';
import {View, TextInput, StyleSheet} from 'react-native';
class Home extends Component {
constructor(props) {
super(props);
this.state = {
text: '',
};
}
render() {
return (
<View style={styles.container}>
<TextInput
style={{height: 40}}
placeholder="Type here!"
autoFocus={true}
onChangeText={(text) => this.setState({text})}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white',
},
});
export default Home;
Function based component
import React, {useState} from 'react';
import {StyleSheet, TextInput, View} from 'react-native';
const Home = () => {
const [input, setInput] = useState('');
return (
<View style={styles.container}>
<TextInput
style={{height: 40}}
placeholder="Type here!"
autoFocus={true}
value={input}
onChangeText={(text) => setInput(text)}
/>
</View>
);
};
export default Home;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white',
},
});
The output is as given below:

If you want more information on this then don’t hesitate to refer official documentation here.