#Image Src Issue

17 messages · Page 1 of 1 (latest)

torn hull
#

I am building a project on React. it's a job filtering web app but the problem is, when i'm trying to use JSON data as image src but it is not working even when the address is correct.
but then I tried to check if importing image was working or not as an individual image source seems like it is working.
but it is not possible to individually import all images when the address is correct in JSON data.

here I'm providing the file structure with my code and also JSON data structure If anyone can address the issue it will be a great help, Thank you.

worn notch
#

I believe you need to dynamically import your image inside your component here is an old answer which explains the different imports.
#988308849305980928 message

torn hull
#

import React from 'react'
import jsonData from '../data.json';
import defaultpic from '../images/myhome.png'

const Main = () => {

const defaultImage = defaultpic

const jobHtml = jsonData.map((data) => {

    const importImage = src => {
        try {
            return require(src);
        } catch (err) {
            return defaultImage;
        }
    }


    return (
        <div className='job-card' key={data.id}>
            <img className='logo'
                src={importImage(data.logo)}
                alt={`${data.company} logo`}
            />
worn notch
#

what is the source of the image?

#

Would you be able to share a repo with us?

torn hull
torn hull
worn notch
#

you only need to store the name of the image, you cannot store the relative path

#

theny you will need to define the path inside require.

#

Proof that it works

#

If the images would live in the cloud storage, you would be able to store the whole URI to that resource, but this project will get bundled up, files will be moved around.

#

The bundler cannot be able to determine where ../images/XYZ if it the path itself is not defined in the require function. If the path is included, it can keep the reference to that directory during bundling.

#

At least this is what I suspect, and it makes sense.

torn hull
#

Now it is working, thanks for the co-operation actually didn't know about require method now got it.

torn hull
# worn notch Proof that it works

Actually, the problem I guess, was in the JSON file, the source of images was defined with full address, so when I'm trying to use it in the require method with the reference, the whole path itself is getting repeated , therefore the bundler couldn't address the source

torn hull