React Native
State and events
Write interaction with useState and onPress.
State with useState
Now we will use useState to track the user input and the added items. We define two state variables: text (the input text) and items (the array of added items). We import useState from the react package.
const [text, setText] = useState('');
const [items, setItems] = useState([]);
We bind the value property of TextInput to text and the onChangeText property to setText. This way each time the user presses a key text is updated and the input field re-renders.
Adding with onPress
To add an item we place a Button. When pressed the onPress event fires; here we add text to the items array and clear text. This way the list grows as the user adds items.
<Button
title="Add"
onPress={() => {
setItems([...items, text]);
setText('');
}}
/>
With [...items, text] we append the new item to the old array. With setText('') we clear the input field. We display the added items with items.map.
Exercise Your turn: state and add button
Import useState from react. Define two useState calls in App for text and items. Give the TextInput value={text} and onChangeText={setText}. Add a <Button title="Add" /> and in its onPress call setItems([...items, text]) and setText('').
Show example solution
import { useState } from 'react';
import { View, Text, TextInput, Button, StyleSheet } from 'react-native';
export default function App() {
const [text, setText] = useState('');
const [items, setItems] = useState([]);
return (
<View style={styles.container}>
<Text>Shopping List</Text>
<TextInput value={text} onChangeText={setText} placeholder="Item name" style={styles.input} />
<Button title="Add" onPress={() => { setItems([...items, text]); setText(''); }} />
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, padding: 16 },
input: { borderWidth: 1, padding: 8, marginBottom: 8 },
});
Test yourself
-
What does useState return?
const [v, setV] = useState(0)
- A component
- A string
- An array: [value, function]
- A number
Show answer
An array: [value, function] — useState returns a [value, function] pair.
-
Fill in the blank: useState call
const [text, setText] = ____('');
Show answer
const [text, setText] = useState('');
-
Match: concept and usage
- useState
- holding state
- onPress
- button press
- setText
- state update
Next lesson: Navigation