React Native
Task list
Write the task list with FlatList.
Task list with FlatList
To show tasks on the screen you use FlatList. It takes three props: data for the array, renderItem for how to draw each item, and keyExtractor to return a unique key for each item. FlatList only renders the items that are visible; even thousands of items stay smooth.
Example: <FlatList data={tasks} renderItem={({ item }) => <Text>{item.text}</Text>} keyExtractor={(item) => item.id} />. renderItem receives an object whose item property is one task from the array. keyExtractor returns item.id as the unique key.
Exercise Add the FlatList
Add a FlatList to the list. Use data={tasks}, renderItem={({ item }) => <Text>{item.text}</Text>}, keyExtractor={(item) => item.id}. Place it below the button.
Show example solution
import React from 'react';
import { SafeAreaView, View, Text, TextInput, Button, FlatList, StyleSheet } from 'react-native';
export default function App() {
const [task, setTask] = React.useState('');
const [tasks, setTasks] = React.useState([]);
const addTask = () => {
setTasks([...tasks, { id: Date.now().toString(), text: task, done: false }]);
setTask('');
};
return (
<SafeAreaView style={styles.container}>
<Text>To-do</Text>
<TextInput placeholder="New task" value={task} onChangeText={setTask} />
<Button title="Add" onPress={addTask} />
<FlatList
data={tasks}
renderItem={({ item }) => <Text>{item.text}</Text>}
keyExtractor={(item) => item.id}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: { flex: 1, padding: 16 }
});
The renderItem pattern
renderItem is an arrow function that takes an object as its parameter. The most used property of this object is item, which is the current array element. The shape is renderItem={({ item }) => ...}. The nested curly braces are JavaScript object destructuring.
You can return any component inside: a Text, a View or a TouchableOpacity. For example renderItem={({ item }) => <Text>{item.text}</Text>} shows each task's text. Later you will use item.done to strike through completed tasks.
Test yourself
-
How do you give a unique key in FlatList?
<FlatList
data={tasks}
renderItem={...}
???={(item) => item.id}
/>
- keyExtractor
- id
- uniqueKey
- key
Show answer
keyExtractor — keyExtractor returns the unique key for each item.
-
Write the keyExtractor body
keyExtractor={(item) =>____}
Show answer
keyExtractor={(item) =>item.id}
-
Match each FlatList prop to its job
- data
- Array to list
- renderItem
- Draws each item
- keyExtractor
- Produces a unique key
- item
- The current item
Next lesson: Completing tasks