Product list
- React Native course
- Intermediate
- Lesson 66/116
- 6 min
Write the product list with FlatList.
Product list with FlatList
To lay the products out on screen we use FlatList. The data prop takes the products array; renderItem draws each product; keyExtractor returns each product's id as the key.
The renderItem parameter is an object whose item property is the current product. <Text>{item.name} - {item.price}</Text> draws each row.
renderItem
renderItem is a function called for each item. It is written as ({ item }) => <Text>{item.name}</Text>. Here item is the current array element.
The JSX returned by the function becomes one row of the list. For a richer row you can wrap it in a View and add styles; for now Text is enough.
Practice Add a FlatList
Add a <FlatList> inside App. Use data={products}, keyExtractor={(item) => item.id} and renderItem={({ item }) => <Text>{item.name} - {item.price}</Text>}.
Starter code
import React from 'react';
import { FlatList, Text, View } from 'react-native';
const products = [
{ id: '1', name: 'Pen', price: 20 },
{ id: '2', name: 'Notebook', price: 35 },
]
export default function App() {
// List the products with FlatList
return (
<View>
<Text>Store</Text>
</View>
);
}Sample solution
import React from 'react';
import { FlatList, Text, View } from 'react-native';
const products = [
{ id: '1', name: 'Pen', price: 20 },
{ id: '2', name: 'Notebook', price: 35 },
]
export default function App() {
return (
<View>
<Text>Store</Text>
<FlatList
data={products}
keyExtractor={(item) => item.id}
renderItem={({ item }) => <Text>{item.name} - {item.price}</Text>}
/>
</View>
);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the data prop
<FlatList ____={products} keyExtractor={keyExtractor} renderItem={renderItem} />
<FlatList data={products} keyExtractor={keyExtractor} renderItem={renderItem} />
Explanation: The data prop takes the products array.
2 What does keyExtractor return?
- The product name
- The unique id Correct answer
- The price
- The array index
Explanation: keyExtractor returns each product's unique id.
3 Match the FlatList props
| Term | Meaning |
|---|---|
data |
Product array |
renderItem |
Draws a row |
keyExtractor |
Returns key |
item |
Current product |