Reputation: 101
I'm creating a small application with React Native that has a local SQLite database for storing images but having trouble rendering my array of images (fetched from the local database and stored in the local state).
Before I was rendered by mapping the data and that worked fine.
state = {
items:[when the user uses the app this array fills with images],
};
<ScrollView>
{items.map(({ id, value }) => (
<TouchableOpacity onPress={this.deletePhoto}
key={id}>
<Image source={{ uri: value }} style={{ width: null, height: 400 }} />
</TouchableOpacity>
))}
</ScrollView>
);
}
But now I would like to go a step further and render the data in a FlatList with my choice of formatting (a grid). Although I can get the FlatList to render the number of images within the array, I can't get the actual image to show. I'm not sure how to pass the data successfully?
renderItem = ({ id, value }) => {
const { items } = this.state;
if (items.empty === true) {
return <View style={[styles.item, styles.itemInvisible]} />;
}
return (
<TouchableOpacity style={styles.item} onPress={this.deletePhoto} key={id}>
<Image source={{ uri: value }} style={{ width: null, height: 400 }} />
</TouchableOpacity>
);
};
For context, this is the creation of the 'items' SQL Table with the 'id' and 'value' attributes:
componentDidMount() {
db.transaction(tx => {
tx.executeSql(
'create table if not exists items (id integer primary key not null, value text);'
);
});
}
I guess the question is, how do I pass/access the attributes of the items array into a functional component?
Update:
https://ibb.co/hMY1qBy (What I'm getting - e.g DB Entry creating a View but no image rendering) https://ibb.co/RN4rqyK (What I'm getting from the answer below)
Upvotes: 0
Views: 2941
Reputation: 3187
After getting a reproducible code from your repo that you shared I manage to render the images in the list.
Here is your renderItem
function
renderItem = ({ item }) => {
const { items } = this.state;
if (items.empty === true) {
return <View style={[styles.item, styles.itemInvisible]} />;
}
return (
<TouchableOpacity style={styles.item} onPress={this.deletePhoto} key={item.id}>
<Image source={{ uri: item.value }} style={{ width: 400, height: 120 }} />
</TouchableOpacity>
);
};
You have to get the item
from your params of the renderItem
function as well you have to pass width to image for rendering, The above code is working fine.
Upvotes: 1
Reputation: 16334
The flatlist renderItem prop gets a argument with multiple properties the main ones will be item and index which are commonly used to access the item in of the row you can use item like below
<FlatList
data={items}
renderItem={({ item }) => (
<TouchableOpacity style={styles.item} onPress={this.deletePhoto} key={item.id}>
<Image source={{ uri: item.value }} style={{ width: null, height: 400 }} />
</TouchableOpacity>
)}
keyExtractor={item => item.id}
/>
Upvotes: 0