Getting User Input
The TextInput component is how you get text input from users in React Native. Whether it's a login form, search bar, or chat message box, TextInput is the component you'll use. It works similarly to an HTML input but with mobile-specific features like different keyboard types.
TextInput is a controlled component — you manage its value through state. This means you control what text appears in the input and can respond to changes in real time.
Basic TextInput
Here's a simple TextInput that captures user input:
import React, { useState } from 'react';
import { TextInput, View, Text, StyleSheet } from 'react-native';
function SearchBar() {
const [query, setQuery] = useState('');
return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder="Search..."
value={query}
onChangeText={(text) => setQuery(text)}
/>
<Text>You typed: {query}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: { padding: 20 },
input: {
height: 44,
borderWidth: 1,
borderColor: '#ccc',
borderRadius: 8,
paddingHorizontal: 12,
fontSize: 16,
},
});
export default SearchBar;
The value prop sets what text is displayed, and onChangeText fires whenever the text changes. The placeholder shows gray text when the input is empty. Together, these create a controlled input where you always know the current value.
Keyboard Types
Different types of input need different keyboards. A phone number field should show a numeric keyboard, while an email field should show one with the @ symbol. TextInput lets you specify this with the keyboardType prop.
<TextInput
keyboardType="default"
placeholder="Default keyboard"
/>
<TextInput
keyboardType="email-address"
placeholder="Email keyboard"
/>
<TextInput
keyboardType="numeric"
placeholder="Number keyboard"
/>
<TextInput
keyboardType="phone-pad"
placeholder="Phone keyboard"
/>
Common keyboard types include default, email-address, numeric, phone-pad, and url. Choosing the right keyboard type improves the user experience by making input faster and more intuitive.
Secure and Multi-Line Inputs
TextInput supports different modes for special use cases. For passwords, use secureTextEntry to hide the text. For longer text like messages or comments, use multiline.
<TextInput
secureTextEntry={true}
placeholder="Password"
style={styles.input}
/>
<TextInput
multiline={true}
numberOfLines={4}
placeholder="Write a message..."
style={[styles.input, { height: 100, textAlignVertical: 'top' ]}
/>
The secureTextEntry shows dots instead of characters, and multiline allows the input to expand as the user types. You can also set numberOfLines to give the input an initial height. These props cover most common input scenarios in mobile apps.