As I continue to learn, I am working on a delivery layout project. I have come across a section where I need to load Cards with restaurant information. The names are displaying correctly, but I am facing issues with loading the images. I am using a JSON file with a 'restaurants' type, which includes id, name, and image.
Here is the file structure:
/
|--/src
|--/App
| |--index.tsx
|--/components
| |--/restaurants
| |--index.tsx
| |--/restaurantCard
| |--index.tsx
|--/assets
|--/restaurants
|--all images png
The RestaurantCard Component:
import { View, Text, Pressable, Image } from 'react-native'
import { RestaurantsProps } from '..'
import { FontAwesome, Ionicons } from '@expo/vector-icons'
export default function RestaurantCard({ item }: { item: RestaurantsProps }) {
const width = 140;
const height = 100;
// This line works
const Logo = Image.resolveAssetSource(require(`@/src/assets/restaurants/kfc.png`)).uri
// This doesn't work
// const Logo = Image.resolveAssetSource(require(`@/src/assets/restaurants/${item.image}`)).uri
return (
<Pressable style={{
marginVertical: 4,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#c8c8c8',
borderRadius: 16,
}}
onPress={() => { console.log(`CLICOU EM ${item.name}`) }}
>
<View style={{
width: width,
height: height,
backgroundColor: 'black',
borderRadius: 16,
}}>
<Image source={{uri: Logo}} style={{
width: width,
height: height,
resizeMode: 'stretch',
borderRadius: 16,
}} />
</View>
<FontAwesome name='circle' size={38} color={'#aaa'} style={{
position: 'absolute',
bottom: 26,
}} />
<Ionicons name='fast-food-outline' size={24} style={{
position: 'absolute',
bottom: 32,
color: '#ddd'
}} />
<Text className='font-semibold text-gray-600 text-lg mt-5'>{item.name}</Text>
</Pressable>
)
}
The Restaurant list component:
import { useEffect, useState } from 'react'
import { View, FlatList } from 'react-native'
import RestaurantCard from './restaurantCard';
import * as restaurantesJson from '@/db.json'
export interface RestaurantsProps {
id: string;
name: string;
image: string
}
export function Restaurants({ urlFetch }: { urlFetch: string }) {
const [restaurants, setRestaurants] = useState<RestaurantsProps[]>([])
useEffect(() => {
//This async function was an attempt, but nothing changed
async function getRestaurantsJson() {
// console.log(data);
setRestaurants(restaurantesJson.restaurants);
console.log(restaurants);
}
getRestaurantsJson()
}, []);
return (
<View>
<FlatList
horizontal={true}
data={restaurants}
renderItem={({ item }) => <RestaurantCard item={item} />}
showsHorizontalScrollIndicator={false}
contentContainerStyle={{
gap: 12,
justifyContent: 'center',
alignItems: "center"
}}
/>
</View>
)
}
I am currently seeking a solution that automatically loads the images without requiring manual file exports.