How to Use TextInput in React Native: Simple Guide
In React Native, use the
TextInput component to let users enter text. Import it from react-native, then include <TextInput /> in your JSX with props like value and onChangeText to handle input changes.Syntax
The TextInput component is imported from react-native. It accepts props like value for the current text, onChangeText to update the text, and placeholder to show a hint.
Example props explained:
- value: The text shown inside the input.
- onChangeText: A function called when the text changes.
- placeholder: Text shown when input is empty.
javascript
import React, { useState } from 'react'; import { TextInput } from 'react-native'; export default function MyInput() { const [text, setText] = useState(''); return ( <TextInput value={text} onChangeText={setText} placeholder="Type here" /> ); }
Example
This example shows a simple input box where users can type text. The typed text is saved in state and displayed below the input.
javascript
import React, { useState } from 'react'; import { View, TextInput, Text, StyleSheet } from 'react-native'; export default function App() { const [text, setText] = useState(''); return ( <View style={styles.container}> <TextInput style={styles.input} value={text} onChangeText={setText} placeholder="Enter your name" /> <Text style={styles.output}>You typed: {text}</Text> </View> ); } const styles = StyleSheet.create({ container: { padding: 20, marginTop: 50 }, input: { height: 40, borderColor: 'gray', borderWidth: 1, paddingHorizontal: 10 }, output: { marginTop: 20, fontSize: 16 } });
Output
A screen with a text input box labeled 'Enter your name'. Below it, typed text appears as 'You typed: [your input]'.
Common Pitfalls
Common mistakes when using TextInput include:
- Not controlling the input with
valueandonChangeText, causing the input to be uncontrolled. - Forgetting to update state inside
onChangeText, so the input does not reflect user typing. - Not styling the input, making it hard to see or use.
javascript
/* Wrong: Missing onChangeText, input won't update */ <TextInput value={text} placeholder="Type here" /> /* Right: Controlled input with state update */ <TextInput value={text} onChangeText={setText} placeholder="Type here" />
Quick Reference
Here are key props for TextInput:
| Prop | Description |
|---|---|
| value | Current text value in the input |
| onChangeText | Function called with new text when user types |
| placeholder | Hint text shown when input is empty |
| secureTextEntry | Hides text input (for passwords) |
| keyboardType | Type of keyboard shown (e.g., numeric, email) |
| multiline | Allows multiple lines of text |
Key Takeaways
Use
TextInput with value and onChangeText to control user input.Always update state inside
onChangeText to reflect typed text.Add
placeholder to guide users on what to type.Style
TextInput for better usability and visibility.Use props like
secureTextEntry for passwords and keyboardType for input type.