React Native
Components
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.
Exercise 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.
Show example 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 },
});
Test yourself
-
Fill in the blank: import TextInput
import { View, Text, ____, StyleSheet } from 'react-native';
Show answer
import { View, Text, TextInput, StyleSheet } from 'react-native';
-
What is TextInput used for?
<TextInput placeholder="Item name" />
- To display text
- To receive text from the user
- To apply styles
- To transition screens
Show answer
To receive text from the user — The user types text with TextInput.
-
Match: TextInput property and role
- placeholder
- hint text
- value
- input value
- onChangeText
- text change
Next lesson: State and events