0

I tried to get dynamically the directory of the images using require but doesn't work

import React from 'react';
import './produto.css'


function Produto({data}) {

    const { id, name, price, score, image } = data;

    return <div className = 'produto-card-container' key = {id}>

        <div className = 'produto-card-flex'>
            <img alt = {image} src = {require(`../../Assets/${image}`)}/>
         
        </div>
    </div>
}

export default Produto;

but in my page the image appear likes this enter image description here

i tried to console the path and the image name to see what's happened My console log of the const image

super-mario-odyssey.png
produto.js:8 call-of-duty-infinite-warfare.png
produto.js:8 the-witcher-iii-wild-hunt.png
produto.js:8 call-of-duty-wwii.png
produto.js:8 mortal-kombat-xl.png
produto.js:8 shards-of-darkness.png
produto.js:8 terra-media-sombras-de-mordor.png
produto.js:8 fifa-18.png
produto.js:8 horizon-zero-dawn.png

2 Answers 2

1

Remember "require returns an object and image's path can be ejected from its default property".

So you must change the following code:

<img alt = {image} src = {require(`../../Assets/${image}`)}/>

To :

<img alt={image} src={require(`../../Assets/${image}.png`).default}/>

Note: If you want to use multi image formats, add imageFormat key to your json db and pass it's value as props.

{
    ...
    image: 'assassins-creed',
    imageFormat : 'jpg'
}

So if you do that, your code must be like to:

const {id, name, price, score, image, imageFormat} = data;

<img alt={image} src={require(`../../Assets/${image}.${imageFormat}`).default}/>

Good luck.

Sign up to request clarification or add additional context in comments.

Comments

1

It's necessary to indicate the type of image. In your case, it is a png.

 <img alt = {image} src = {require(`../../Assets/${image}.png`)}/>

4 Comments

but in my json db the image is already saved as a png
I dont understand why if you have the image in /Assets/ location you need to search to get dynamically the directory
I have a json db, with products, and the products have i index called 'image' where then have the image name, and the images file is saved in the assets folder
You can test to put all path C:/Asstest/.. where you have the images. I think that the sistem is showing and string and not a image

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.