Components
- React Native course
- Beginner
- Lesson 113/116
- 6 min
Set up View, Text and TextInput components.
Adding TextInput
The skeleton is ready. Now we will add a TextInput to receive product names from the user. TextInput is the field where the user types text with the keyboard. You provide the hint text shown when empty with the placeholder property.
We place a <TextInput> below the <Text> in the skeleton. We add an input style to StyleSheet: a border and padding visualize the input field. We also import TextInput from the react-native package.
Placeholder and style
The placeholder property of TextInput is the hint text shown when the input is empty. For example if you write placeholder="Item name", when the user has not typed anything yet a gray "Item name" appears. When the user starts typing this text disappears.
To visualize the input field you define an input style in StyleSheet: borderWidth: 1 for a thin border, padding: 8 for inner spacing, marginBottom: 8 for space below. This makes the input field clear and usable.
Practice Your turn: add TextInput
Add a TextInput to the skeleton. Include TextInput in the react-native import. Below the title place <TextInput placeholder="Item name" style={styles.input} />. Add an input style to StyleSheet: borderWidth: 1, padding: 8, marginBottom: 8.
Starter code
import { View, Text, StyleSheet } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Text>Shopping List</Text>
{/* add a TextInput */}
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, padding: 16 },
});Sample solution
import { View, Text, TextInput, StyleSheet } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Text>Shopping List</Text>
<TextInput placeholder="Item name" style={styles.input} />
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, padding: 16 },
input: { borderWidth: 1, padding: 8, marginBottom: 8 },
});Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: import TextInput
import { View, Text, ____, StyleSheet } from 'react-native';
import { View, Text, TextInput, StyleSheet } from 'react-native';
Explanation: TextInput is imported from the react-native package.
2 What is TextInput used for?
<TextInput placeholder="Item name" />- To display text
- To receive text from the user Correct answer
- To apply styles
- To transition screens
Explanation: The user types text with TextInput.
3 Match: TextInput property and role
| Term | Meaning |
|---|---|
placeholder |
hint text |
value |
input value |
onChangeText |
text change |