Seeking assistance with integrating images into a flatlist grid. I have successfully implemented text but struggling with images stored in the assets folder.
The goal is to display separate images from the assets folder within the boxes of the flatlist grid.
If more details are needed, please let me know!
Below is the code snippet:
import React from 'react';
import { View, Image, Text, StyleSheet, TouchableOpacity, FlatList, Dimensions } from 'react-native';
import { drawer } from '../navigation/AppNavigation';
import { hp, wp } from '../utils/responsiveScreen';
const dataList = [{ key: '1' }, { key: '2' }, { key: '3' }, { key: '4' }, { key: '5' },{ key: '6' },{ key: '6' },{ key: '6' }];
const numColumns = 2;
const WIDTH = Dimensions.get('window').width;
const Main = () => {
formatData = (data, numColumns) => {
const totalRows = Math.floor(data.length / numColumns);
let totalLastRow = dataList.length - (totalRows * numColumns);
while(totalLastRow !== 0 && totalLastRow !== numColumns){
dataList.push({'key': 'blank', empty: true});
totalLastRow++;
}
return dataList;
};
_renderItem = ({ item, index }) => {
let {itemStyle, itemText} = styles;
if(item.empty){
return <View style={[itemStyle]}/>;
}
return (
<View style={itemStyle}>
<Text style={styles.itemText}>{item.key}</Text>
</View>
);
};
return (
<View style={styles.container}>
<TouchableOpacity
style={{ height: 50 }}
onPress={() => drawer.current.open()}>
<Image source={require('../assets/menu.png')} />
</TouchableOpacity>
<Text style={styles.textStyle}>Stars</Text>
<FlatList
data={this.formatData(dataList, numColumns)}
renderItem={this._renderItem}
keyExtractor={(item, index) => index.toString()}
numColumns={numColumns}
/>
</View>
);
};
And here is the Style sheet:
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
paddingTop: hp(7),
paddingHorizontal: wp(6),
},
textStyle: {
marginBottom: 20,
fontWeight: 'bold',
fontSize: 24,
color: 'black',
},
image: {
alignSelf: 'center',
height: hp(40),
width: hp(40),
marginTop: hp(3),
},
itemStyle: {
backgroundColor: 'pink',
alignItems: 'center',
justifyContent: 'center',
height: 150,
flex: 1,
margin:1,
width: WIDTH / numColumns
},
itemText: {
fontSize: 50
}
});
Showing a preview of the current layout: Here
UPDATE
Updated the datalist as follows:
const dataList = [{ key: '1', image: require('../assets/backGround.png')}, { key: '2', image: require('../assets/backGround.png') }, { key: '3', image: require('../assets/backGround.png')}];
Adjusted the view like this:
<View style={itemStyle}>
{/* <Text style={styles.itemText}>{item.key}</Text> */}
<Image
style={styles.image}
source={item.image}
/>
</View>
Encountering an error now:
TypeError: 'required' is not a function. The issue occurs when trying to fetch the image ('require('../assets/backGround.png')'), where 'require' seems to be undefined.