Reputation: 1727
I have created cardView but how can I convert it to <FlatList/>
I am not able to understand what should be the renderItem
of FlatList
?
My current code:
<ScrollView style={styles.container}>
<View style={styles.cardView}>
<Text style={styles.projectName}>{marketing_updates.length != 0 ? marketing_updates[0].project_name: ""}</Text>
<Text style={styles.title}>{marketing_updates.length != 0 ? marketing_updates[0].title: ""}</Text>
<Text style={styles.description}>Description: {marketing_updates.length != 0 ? marketing_updates[0].description: ""}</Text>
<Image
style={styles.img}
source={{uri: marketing_updates.length != 0 ? marketing_updates[0].image: null}}
/>
<View style={styles.buttons}>
<Text style={styles.like}>Like</Text>
<Text style={styles.share}>Share</Text>
</View>
<View style={styles.comment}>
<Text>Comments: </Text>
<Text>comment 1</Text>
<Text>comment 2</Text>
<Text>comment 3</Text>
</View>
</View>
</ScrollView>
How can I convert it to FlatList ?
What I tried :
<ScrollView style={styles.container}>
<FlatList
data={marketing_updates.length != 0 && marketing_updates ? marketing_updates : null}
renderItem={}
/>
</ScrollView>
I am not able to understand what should be there inside renderItem={}
?
Upvotes: 1
Views: 877
Reputation: 8856
renderItem
accepts a function which takes the current list item as an argument and renders a component. You can think of it as the "map" function like in listItems.map(item => <MyListItem {...item} />
.
I'd recommend you create a presentational "card" component to encapsulate the view rendering logic (e.g. MarketingUpdateCard
) and just pass the list item data as props:
renderItem={({ item }) => (
<MarketingUpdateCard {...item} />
)}
And an example card component:
// MarketingUpdateCard.js
const MarketingUpdateCard = ({ project_name, title, description, image }) => (
<View>
// your current card template here
</View>
)
Upvotes: 2
Reputation: 958
According to the react-native docs the "renderItem" does the following:
Takes an item from data and renders it into the list.
So you can pass any kind of react component to it and the flat list will use this component as for every item inside your list. In your case you can do the following:
move your "CardView" to a new Component called for example "CardViewComponent".
Then you can do following to create a flatlist:
<FlatList
data={marketing_updates.length != 0 && marketing_updates ? marketing_updates : null}
renderItem={({item}) => {
<CardViewComponent marketingData={marketing_updates[item.index]}/>
}}
/>
Upvotes: 1
Reputation: 1227
The renderItem
prop should be a function that returns a react-native component
See there : https://facebook.github.io/react-native/docs/flatlist#renderitem
data={marketing_updates}
renderItem = {
(update) => {
<Text>
update.project_name
</Text>
}
}
The renderItem()
method will be called for each element of your marketing_updates
array.
Upvotes: 2