i'm currently trying to implement a horizontal FlatList. I'm aware that i can render list of items pretty easly inside the renderItem by just looping it through... but can i actually pass a custom component inside ?
This is my array filled with custom components i created:
const arrayOfCustomComponents = [<Home/>,<News/>,<History/>,<Stats/>,<Settings />];
Given this array, can i pass each index inside renderItem to be rendered ?
<Animated.FlatList
data={data}
keyExtractor={item => item.key}
horizontal
showsHorizontalScrollIndicator={false}
pagingEnabled
bounces={false}
renderItem={({item}) =>{
return <View>
{arrayOfCustomComponents[item.key]}
</View>
}}
/>
CodePudding user response:
You cannot access an array
elements like you've done in your example. The keys of an array are 0, 1, 2, ....
What you can do instead is to store your components in an object like that:
const DATA = [
{
id: 'comp1',
description: 'This is component 1',
},
{
id: 'comp2',
description: 'This is component 2',
}
];
const Comp1 = () => {
return (
<View><Text>This is component 1</Text></View>
)
}
const Comp2 = () => {
return (
<View><Text>This is component 2</Text></View>
)
}
const mapOfComponents = {
comp1: <Comp1 />,
comp2: <Comp2 />
};
function App() {
return (
<View>
<FlatList
data={DATA}
renderItem={({ item }) => {
return (
mapOfComponents[item.id]
)
}
}
keyExtractor={item => item.id}
/>
</View>
);
}