I am trying to load images dynamically using a local file path. All the images are stored inside the assets folder and a server api responds with which image to display on different screens. It is required to load images dynamically instead of hardcoding as I’m trying to render images randomly. Appreciate your support to resolve this.
This is the error I got when running the app while passing a filename as a parameter to require(). I'm aware that this works if it's hardcoded file path.
error: index.js: Invalid call at line 36: require(item)
import React,{useState} from "react";
import { Text, View, Image, FlatList} from "react-native";
const MyComponent=()=>{
// this list is loaded from an api
const imagesList = ["../../../assets/images/apple.png", "../../../assets/images/flower.png" ];
return(
<View>
<FlatList
contentContainerStyle={styles.grid}
numColumns={3}
data={imagesList}
keyExtractor={(item,index) =>index.toString()}
renderItem={(item)=>{
//line 36
return(<Image source={require(item)} />); }} />
</View>);
}
What I’m expecting to render is something like below: enter image description here
