I am currently struggling with rendering some images on my React Native application. Currently, my app is connected to a database, which contains the image file names (ex: ‘swipe1’) that I want to render in my FlatList. However, it is my understanding that React Native has an issue with this due to its dynamic nature. All of the images I want to use are already saved in a local folder within the app, so I just want the app to be able to pull the picture name from the database and render it. Help!
const CardList = () => {
const [data, setData] = useState([])
useEffect(()=>{
fetch('http://127.0.0.1:xxxx/', {
method:'GET'
})
.then(resp => resp.json())
.then(listing => {
setData(listing)
})
}, [])
const compileImagePath = (imageName) => {
return `../../assets/images/${imageName}.png`;
};
return (
<FlatList
data={data}
keyExtractor={item => item.id}
renderItem={({item, index}) => {
const imagePath = compileImagePath(item.image);
console.log(imagePath)
return (
<Image source={require(imagePath)} style={styles.image} />
);
}}
/>
);
};
export default CardList;
2
Answers
You need to be sure that your RN project is configured to bundle the assets in with your JS bundle. This is something that is pretty easy to do with Expo. I’m not sure what the configuration steps would be for a bare RN project.
Static assets like images, fonts,… need to be declared to be embedded in the app at compile-time. App can NOT dynamically load static assets at run-time.
Possible solution :
1. Host images on your servers or use public cloud providers, S3 , Cloudinary….
2. Declare required static images to compile-time
Inside top-level file (
App.js
)Later in your
Card
component