Data
// Dummy data array
const data = [
{id: 1, name: 'Tom'},
{id: 2, name: 'Jerry'},
]
Solution #1
You can make a custom component for that like this:
const VirtualizedList = ({children}) => {
return (
<FlatList
data={[]}
keyExtractor={() => "key"}
renderItem={null}
ListHeaderComponent={
<>{children}</>
}
/>
)
}
Then use this VirtualizedList as the parent component:
...
return (
<VirtualizedList>
<FlatList
data={data}
keyExtractor={(item, index) => item.id + index.toString()}
renderItem={_renderItem}
/>
<AnyComponent/>
</VirtualizedList>
)
Solution #2
If you use FlatList inside the ScrollView, it gives a warning which is annoying, so you can use the array's map property, like this:
Note*: It is not recommended way to show list. If you have a small amount of that, then you can use it that's totally fine, but if you want to show a list which get data from an API and have lots of data, then you can go with other solutions. If you use a map with large data, then it affects your app's performance.
<ScrollView>
{data.map((item, index) => (
<View key={index}>
<Text>{item.name}</Text>
</View>
))}
</ScrollView>
Solution #3
If you make your FlatList horizontal (as per your need) then also the warning will disappear:
<ScrollView>
<FlatList
data={data}
keyExtractor={(item, index) => item.id + index.toString()}
horizontal={true}
/>
</ScrollView>
Solution #4
You can add a header and footer component.
In ListHeaderComponent and ListFooterComponent, you can add any component, so you don't need the parent ScrollView.
<FlatList
data={data}
keyExtractor={(item, index) => item.id + index.toString()}
ListHeaderComponent={headerComponent}
ListFooterComponent={footerComponent}
ListEmptyComponent={emptyComponent}
ItemSeparatorComponent={separator}
/>
// List components
const headerComponent = () => (
<View>
<Header/>
<Any/>
</View>
)
const footerComponent = () => (
<View>
<Footer/>
<Any/>
</View>
)
const emptyComponent = () => (
<View>
<EmptyView/>
<Any/>
</View>
)
const separator = () => (
<View style={{height: 0.8, width: '100%', backgroundColor: '#fff'}} />
)
<FlatList />
inside a<ScrollView />
horizontal={false}
(=>vertical) forFlatList
insideScrollView
, just replace theScrollView
with regularView
(if you have more content besidesFlatList
). Don't have any other paralel content in the wrapping view? => simply don't wrap theFlatList
in theScrollView
at all ;-) (SafeAreaView
is iOS only)