0
votes

I have this warning in my project: "Warning: Failed prop type: Invalid prop source supplied to Image". I'm loading an image from sampleProducts.json to Recommendend.js and pass it as props in Products.js, but the image won't load because of the warning.

sampleProducts.json

"recommended": {
    "product1": {
        "id": "1",
        "image": "require('../images/sample1.png')",
        "name": "Sample Product",
    },

Recommmended.js

{Object.values(recommended).map(product => (
                    <Products
                        key={ product.id }
                        productImage={ product.image }
                        productName={ product.name }
                    />
                ))}

Products.js

<Card style={ styles.card }>
                    <CardItem>
                        <Image style={ styles.productImage } source={ productImage} resizeMode='contain' />
                    </CardItem>
                    <CardItem>
                        <Body>
                            <Text style={ styles.productName }>{productName}</Text>
                        </Body>
                    </CardItem>
                </Card>
2
Please post the warning as its outputted to you.Daniel

2 Answers

0
votes

Get rid of the require() on recommended.product1.image and make it just "../images/sample1.jpg"

Change your Image component's source prop to be source={require(`${recommended.product1.image}`)}

0
votes

You cannot use require in JSON format and require not support dynamic path.

Can you use switch case statement instead ?

function getImage(img_name) {
  switch(img_name) {
    case "sample1.png": return require("../images/sample1.png");
    case "sample2.png": return require("../images/sample2.png");
  }
}

and change JSON to

"recommended": {
    "product1": {
        "id": "1",
        "image": "sample1.png",
        "name": "Sample Product",
    }
}

and use with component below

<Image source={getImage(productImage)} />

If you don't want to use switch case check this answers for other methods