|
| 1 | +import React from 'react'; |
| 2 | +import { FlatList, Pressable, StyleSheet, View } from 'react-native'; |
| 3 | + |
| 4 | +type ItemListProps<T> = { |
| 5 | + items: T[]; |
| 6 | + onItemSelected: (item: T) => void; |
| 7 | + title: React.ReactNode; |
| 8 | + itemKey: (item: T, index: number) => string; |
| 9 | + callout?: React.ReactNode; |
| 10 | + empty?: React.ReactNode; |
| 11 | + itemContent: (item: T) => React.ReactNode; |
| 12 | + separator?: React.ReactNode; |
| 13 | +}; |
| 14 | + |
| 15 | +export function ItemList<T>(props: ItemListProps<T>) { |
| 16 | + return ( |
| 17 | + <View style={styles.container}> |
| 18 | + {props.title} |
| 19 | + {props.callout} |
| 20 | + |
| 21 | + {props.items.length === 0 ? ( |
| 22 | + (props.empty ?? null) |
| 23 | + ) : ( |
| 24 | + <FlatList |
| 25 | + data={props.items} |
| 26 | + keyExtractor={props.itemKey} |
| 27 | + ItemSeparatorComponent={() => ( |
| 28 | + <View>{props.separator ?? <View style={styles.separator} />}</View> |
| 29 | + )} |
| 30 | + renderItem={({ item }) => ( |
| 31 | + <View> |
| 32 | + <Pressable onPress={() => props.onItemSelected(item)} style={styles.listItem}> |
| 33 | + {props.itemContent(item)} |
| 34 | + </Pressable> |
| 35 | + </View> |
| 36 | + )} |
| 37 | + /> |
| 38 | + )} |
| 39 | + </View> |
| 40 | + ); |
| 41 | +} |
| 42 | + |
| 43 | +const styles = StyleSheet.create({ |
| 44 | + container: { |
| 45 | + flex: 1, |
| 46 | + width: '100%', |
| 47 | + }, |
| 48 | + listItem: { |
| 49 | + borderColor: '#ddd', |
| 50 | + padding: 16, |
| 51 | + }, |
| 52 | + |
| 53 | + separator: { |
| 54 | + // Default styles, which can be overridden by props |
| 55 | + backgroundColor: '#ccc', // Default color (light gray) |
| 56 | + height: 2, // Determines the thickness of the line |
| 57 | + marginVertical: 5, // Adds some space above and below the line |
| 58 | + width: '100%', // Makes the line span the full width |
| 59 | + }, |
| 60 | +}); |
0 commit comments