Reputation: 1
I'm implementing an app and on the homescreen I have a flatlist element with inside for each item a card element.
import React, { useEffect, useContext } from 'react';
import { Text, View, StyleSheet, FlatList } from 'react-native';
import {ListItem, Card} from 'react-native-elements';
import { Context as ParkingContext } from '../context/ParkingContext';
const HomeScreen = () => {
const { state: {records}, fetchParkings } = useContext(ParkingContext);
useEffect(() => {
fetchParkings();
},[])
return (
<View style={styles.container}>
<FlatList
data={records}
keyExtractor={item => item.recordid}
renderItem={({item}) => {
return (
<Card containerStyle={styles.cardStyle} title={item.fields.description}>
<Text style={styles.textStyle}>{item.fields.address.replace(/\n/g,'')}</Text>
<Text style={styles.textStyle}>Aantal vrije plaatsen: {item.fields.availablecapacity}</Text>
</Card>
)
}}
/>
</View>
)
};
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 25
},
cardStyle: {
padding: 0,
borderRadius: 10
},
textStyle: {
flexDirection: 'row',
flex: 1,
marginBottom: 10,
marginLeft: 5
}
});
export default HomeScreen;
The card element has a property image which can be used to set a image to the card. I want to give different images to the cards by doing
image={require(`../../assets/${item.fields.description}.jpg`)}
but require doesn't let me do this with backticks and neither with a variable... is there some way to use backticks or a variable so I can have different photo's for the different cards?
My apologies if the answer is obvious but I tried a lot of things and it does not work.
Upvotes: 0
Views: 960
Reputation: 1070
Assuming you created your react app with create-react-app
or you are using webpack to bundle your code then what you are trying to achieve will not work: Since Webpack is running in build-time, it can't figure out which modules to bundle when the name is a dynamic variable. Packaging happens once before runtime so those variables don't have values yet.
If you have a small number of images, you can do something like this:
let image1 = require('../../assets/xxx.jpg');
let image2 = require('../../assets/xxx.jpg');
...
image={image1}
...
But of course, if you have a long list of images this way will not be optimal
Further details can be found in the discussion of this issue
Upvotes: 1