Skip to content

Commit ddefd51

Browse files
authored
Potentially confusing extraData flatlist docs
The current example for using extraData in the flatList does not actually require the extraData prop at all. This commit is to contrive an example where extraData in the flatList makes a difference. The existing example runs fine without the extraData prop at all because the functional component re-creates the renderItem function reference on every call to the App function when the selectId state is set. Since the renderItem reference changes to the flatList, it re-renders. In the functional paradigm data needs to be passed to the renderItem method by reference in order to create the need for extraData.
1 parent 686322e commit ddefd51

1 file changed

Lines changed: 20 additions & 12 deletions

File tree

‎docs/flatlist.md‎

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ More complex, selectable example below.
8888
- `keyExtractor` tells the list to use the `id`s for the react keys instead of the default `key` property.
8989

9090
```SnackPlayer name=flatlist-selectable
91-
import React, { useState } from "react";
91+
import React, { useCallback, useState, useRef } from "react";
9292
import { FlatList, SafeAreaView, StatusBar, StyleSheet, Text, TouchableOpacity } from "react-native";
9393
9494
const DATA = [
@@ -113,29 +113,37 @@ const Item = ({ item, onPress, backgroundColor, textColor }) => (
113113
);
114114
115115
const App = () => {
116-
const [selectedId, setSelectedId] = useState(null);
117-
118-
const renderItem = ({ item }) => {
119-
const backgroundColor = item.id === selectedId ? "#6e3b6e" : "#f9c2ff";
120-
const color = item.id === selectedId ? 'white' : 'black';
116+
const [extraData, setExtraData] = useState(null);
117+
const selectIdRef = useRef();
118+
119+
const renderItem = useCallback(({ item }) => {
120+
const backgroundColor =
121+
item.id === selectIdRef.current ? '#6e3b6e' : '#f9c2ff';
122+
const color = item.id === selectIdRef.current ? 'white' : 'black';
123+
const onPress = () => {
124+
selectIdRef.current = item.id;
125+
setExtraData(item.id);
126+
};
121127
122128
return (
123129
<Item
124130
item={item}
125-
onPress={() => setSelectedId(item.id)}
126-
backgroundColor={{ backgroundColor }}
127-
textColor={{ color }}
131+
onPress={onPress}
132+
backgroundColor={{backgroundColor}}
133+
textColor={{color}}
128134
/>
129135
);
130-
};
136+
}, []);
137+
138+
const keyExtractor = useCallback(item => item.id, []);
131139
132140
return (
133141
<SafeAreaView style={styles.container}>
134142
<FlatList
135143
data={DATA}
136144
renderItem={renderItem}
137-
keyExtractor={(item) => item.id}
138-
extraData={selectedId}
145+
keyExtractor={keyExtractor}
146+
extraData={extraData}
139147
/>
140148
</SafeAreaView>
141149
);

0 commit comments

Comments
 (0)