I'm trying to build React-Native app and I have 4 images inside the project and I'm trying to display them through Flatlist. I put the image link into an array. I try to retrieve the images through the Render item, but it shows me this error What am I doing wrong? What is the solution?
my array
const categoryData = [
{
title: 'middle east food',
image: '../assets/image/category1.png',
ALIAS: 'mediterranean, All',
},
{
title: 'mexican food',
image: '../assets/image/category2.jpg',
ALIAS: 'easternmexican',
},
{
title: 'Spanish Food',
image: '../assets/image/category3.png',
ALIAS: 'spanish, All',
},
{
title: 'Turkish Food',
image: '../assets/image/category4.jpg',
ALIAS: 'turkish, All',
},
];
flatListCode
<FlatList
horizontal
data={categoryData}
renderItem={({item}) => (
<Pressable>
<Image source={require(item.image)}/>
<Text>{item.title}</Text>
</Pressable>
)}
/>
error enter image description here
CodePudding user response:
Instead of passing the path as data, You can pass arrow function which renders the Image Component.
const categoryData = [
{
title: 'middle east food',
image: () => <Image source={require('../assets/image/category1.png')} />,
ALIAS: 'mediterranean, All',
},
{
title: 'mexican food',
image: () => <Image source={require('../assets/image/category2.png')} />,
ALIAS: 'easternmexican',
},
{
title: 'Spanish Food',
image: () => <Image source={require('../assets/image/category3.png')} />,
ALIAS: 'spanish, All',
},
{
title: 'Turkish Food',
image: () => <Image source={require('../assets/image/category4.png')} />,
ALIAS: 'turkish, All',
},
];
And Then Simply pass the categoryData to the data prop of FlatList. Also just call the {item.image()}
<FlatList
horizontal
data={categoryData}
renderItem={({item}) => {
return (
<Pressable>
{item.image()}
<Text>{item.title}</Text>
</Pressable>
);
}}
/>
This will Definitely solve your problem mate !
CodePudding user response:
my solution:
const categoryData = [
{
title: 'middle east food',
image: require('../assets/image/category1.png'),
ALIAS: 'mediterranean, All',
},
{
title: 'mexican food',
image: require('../assets/image/category2.jpg'),
ALIAS: 'easternmexican',
},
{
title: 'Spanish Food',
image: require('../assets/image/category3.png'),
ALIAS: 'spanish, All',
},
{
title: 'Turkish Food',
image: require('../assets/image/category4.jpg'),
ALIAS: 'turkish, All',
},
];
<FlatList
horizontal
data={categoryData}
renderItem={({item}) => (
<Pressable>
<Image
showsHorizontalScrollIndicator
resizeMode="stretch"
style={[
styles.categoryImg,
{width: width / 2.25, height: width / 2.25},
]}
source={item.image}
/>
