0
votes

I have the image source from props, when I concatenate source string like: require(../assets/images/${props.image}). Then I call it on the source property of the image I got an error: Failed prop type: Invalid prop source supplied to Image.

Is there anyone can help, thanks so much <3

function Category(props) {
let image = `require(../assets/images/${props.image})`;
console.log(image);
return (
    <TouchableOpacity style={styles.container}>
        <View>
            <Image style={{ width: 60, height: 60 }} source={image}></Image>
            <Image style={{ height: 10, width: 12 }} source={require('../assets/images/Layer1.png')}></Image>

        </View>
        <View></View>
    </TouchableOpacity>
);
}

Category is called by renderItem on FlatList, and item.image is the file name of image: layer1.png, layer2.png... Parent component - MainScreen:

function MainScreen({ navigation }) {
return (
    <Screen style={styles.container}>
        <Header isHome={true}>HOME</Header>
        <ScrollView>
            <View style={styles.main}>
                <Carousel data={bannerSlide} />                 
                <Text>Go to Detail</Text>
                <View style={styles.category}>
                    <FlatList
                        style={styles.dishList}
                        data={dishList}
                        keyExtractor={item => item.label.toString()}
                        horizontal
                        snapToAlignment="center"
                        scrollEventThrottle={16}
                        showsHorizontalScrollIndicator={false}
                        renderItem={({ item }) =>
                            <Category
                                name={item.name}
                                image={item.image}
                            />
                        }
                    />
                </View>
     
            </View>
        </ScrollView>
    </Screen>
);
}
1
need more information in your question. include your parent component where you use Category component.C.K
I just updated my question <3Noname

1 Answers

2
votes

You are trying to pass a string to image variables and the source will fail because you are supplying a string. You need to update it like below

let image = require(`../assets/images/${props.image}`);

require embed all the images before the app rendered on the device and that means you can not use a dynamic local path in require. You can read more info here. Your best approach is to embed the resource in a separate js file and export them from there and then import and reference them wherever you need them.

For example, have a imageManager.js with following code

export default {
   first_image: require('./image.png'); 
}

Then in your component you can use them like below

import images from './imageManager';

function Category(props) {
let image = images[props.image];
...

props.image could be then set to 'first_image' or so on.

Hope this help.