I have a special folder with images in my React Native application. Path to these pictures is stored in the special object that is passed as prop to the Card component. So, I can’t use require, because it uses only static path string. How can I use load these images from my props? There is my try:
JavaScript
x
37
37
1
import React from 'react';
2
import {
3
View,
4
Text,
5
Image,
6
TouchableOpacity,
7
StyleSheet
8
} from 'react-native';
9
import EmptyImage from '../data/images/empty-image.jpg';
10
11
class Card extends React.Component {
12
13
constructor(props) {
14
super(props);
15
}
16
17
render() {
18
19
const { myObject } = this.props;
20
21
return (
22
<View>
23
<Image
24
source={
25
myObject.imagesNames[0] ?
26
require(`../data/images/${myObject.imagesNames[0]}`)
27
:
28
EmptyImage
29
}
30
/>
31
</View>
32
);
33
}
34
}
35
36
export default Card;
37
Advertisement
Answer
As your images are local better create a json object by requiring the images like below
JavaScript
1
5
1
images={
2
image1:require('path'),
3
image2:require('path2'),
4
};
5
And you can set the url like below
JavaScript
1
5
1
<Image source={
2
myObject.imagesNames[0] ?images[imagesNames[0]]:EmptyImage
3
}
4
/>
5