React Native
renderItem
Learn to render each item with renderItem.
renderItem
renderItem is the function that draws each array item. It takes an object as its parameter whose item property is the current element. In JavaScript this pattern is called destructuring: ({ item }).
The function body is free; you can return a single Text or several components inside a View. For a color list, for example, you can write <View style={{ backgroundColor: item.color }}><Text>{item.name}</Text></View> for each item. item is always the current array element, whatever its type.
A custom renderItem
You can write any JSX inside renderItem. For a color list, using a View + Text combination per item shows both the background color and the name. The key is to reference the right field of item.
For example with colors = [{ name: 'Tomato', color: 'tomato' }, { name: 'Sky', color: 'skyblue' }] each object has name and color fields. renderItem={({ item }) => <View style={{ backgroundColor: item.color, padding: 12 }}><Text>{item.name}</Text></View>} draws a styled card for each color.
Exercise Write a color list
Complete the empty component. The colors array is defined: each object has name and color fields. Return <FlatList data={colors} renderItem={({ item }) => <View style={{ backgroundColor: item.color, padding: 12 }}><Text>{item.name}</Text></View>} keyExtractor={(item, index) => index.toString()} />.
Show example solution
import React from 'react';
import { FlatList, View, Text } from 'react-native';
export default function ColorList() {
const colors = [
{ name: 'Tomato', color: 'tomato' },
{ name: 'Sky', color: 'skyblue' }
];
return (
<FlatList
data={colors}
renderItem={({ item }) => (
<View style={{ backgroundColor: item.color, padding: 12 }}>
<Text>{item.name}</Text>
</View>
)}
keyExtractor={(item, index) => index.toString()}
/>
);
}
Test yourself
-
Write the renderItem parameter
renderItem={(____) => <Text>{item.name}</Text>}
Show answer
renderItem={({ item }) => <Text>{item.name}</Text>}
-
What does item in renderItem's parameter represent?
renderItem={({ item }) => <Text>{item}</Text>}
- The current array element
- The item index
- The whole list
- The key value
Show answer
The current array element — item is the current array element.
-
Match each part to its role
- ({ item })
- Object destructuring
- item
- The current item
- renderItem
- Function drawing each item
- <Text>{item.name}</Text>
- Shows the item name
Next lesson: keyExtractor