Skip to content

Commit b1ace00

Browse files
authored
Add support for keyExtractor in SectionList (#762)
1 parent 3f91f00 commit b1ace00

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

example/src/SectionListExample.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ const SwipeableViewExample: React.FC = () => {
5252
listComponent="FlatList"
5353
data={sampleData}
5454
sectionKey="category"
55+
keyExtractor={(item) => item.id?.toString()}
5556
renderItem={({ item }) => (
5657
<View>
5758
<Text>{item?.id}</Text>
@@ -68,6 +69,7 @@ const SwipeableViewExample: React.FC = () => {
6869
data={sampleData}
6970
sectionKey="category"
7071
estimatedItemSize={40}
72+
keyExtractor={(item) => item.id?.toString()}
7173
renderItem={({ item }) => (
7274
<View>
7375
<Text>{item?.id}</Text>

packages/core/src/components/SectionList/SectionList.tsx

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ interface AdditionalSectionListProps<T> {
1414
index: number;
1515
section: string;
1616
}) => JSX.Element;
17+
keyExtractor?: (item: T, index: number) => string;
1718
listComponent?: ListComponentType;
1819
}
1920

@@ -43,6 +44,7 @@ const SectionList = <T extends { [key: string]: any }>({
4344
listComponent = "FlatList",
4445
data: dataProp,
4546
renderItem: renderItemProp,
47+
keyExtractor: keyExtractorProp,
4648
...rest
4749
}: FlatListSectionListProps<T> | FlashListSectionListProps<T>) => {
4850
const data = React.useMemo(
@@ -165,6 +167,17 @@ const SectionList = <T extends { [key: string]: any }>({
165167
}
166168
};
167169

170+
const keyExtractor = (item: SectionListItem<T>, index: number) => {
171+
switch (item.type) {
172+
case "SECTION_ITEM": {
173+
return `section_${index.toString()}`;
174+
}
175+
case "DATA_ITEM": {
176+
return keyExtractorProp?.(item.data, index) || index.toString();
177+
}
178+
}
179+
};
180+
168181
switch (listComponent) {
169182
case "FlatList":
170183
return (
@@ -173,6 +186,7 @@ const SectionList = <T extends { [key: string]: any }>({
173186
{...(rest as FlatListProps<SectionListItem<T>>)}
174187
data={dataWithSections}
175188
renderItem={renderItem}
189+
keyExtractor={keyExtractor}
176190
/>
177191
);
178192
case "FlashList":
@@ -182,6 +196,7 @@ const SectionList = <T extends { [key: string]: any }>({
182196
{...(rest as FlashListProps<SectionListItem<T>>)}
183197
data={dataWithSections}
184198
renderItem={renderItem}
199+
keyExtractor={keyExtractor}
185200
/>
186201
);
187202
}

0 commit comments

Comments
 (0)