javascriptjsonreactjsimagesrc

Not loading images on React using a JSON object as reference


this is my problem

I have this object Json below:

const imagesData = [
    {
        "imagepath": "./images/a.jpg",
        "title": "Red Car",
        "uploadeDate": "2 May 2020",
        "index": "0"
    }, {
        "imagepath": "./images/b.jpg",
        "title": "Blue Car",
        "uploadeDate": "2 May 2020",
        "index": "1"
    }, {
        "imagepath": "./images/c.jpg",
        "title": "Green Car",
        "uploadeDate": "2 May 2020",
        "index": "2"
    }

]

So my code is using the property of this object called "imagepath" to use it on the src of the tag img

const card = imagesData.map(function (obj, ind) {
       
        return (
            <div className='card'>
                <img src={obj.imagepath} />
                <span>{obj.title}</span>
            </div>
        )

so the problem is that the images are not loading, i have already checked the path and it is right

this is a picture of how it shows on my screen:

enter image description here

One observation is that if i try to import the images by import car1 from './images/a.jpg

and after this i put the variable car1 like below <img src={car1} />

it works fine !. But i need a solution that i reference that path of the image from a json object !


Solution

  • I think you should keep your images folder in the public Folder and then you can try this directly without importing.

    const imagesData = [
        {
            "imagepath": '/images/a.jpg',
            "title": "Red Car",
            "uploadeDate": "2 May 2020",
            "index": "0"
        }, {
            "imagepath": '/images/b.jpg',
            "title": "Blue Car",
            "uploadeDate": "2 May 2020",
            "index": "1"
        }, {
            "imagepath": '/images/c.jpg',
            "title": "Green Car",
            "uploadeDate": "2 May 2020",
            "index": "2"
        }
    
    ]