skip to Main Content

I have a data.js file, and from that file, I am trying to display some images. Here is my example data.js file:

const data = {
  lists: [
    {
      image: "../assets/images/collection/23.png",
    },
    {
      image: "../assets/images/collection/422.png",
    },
  ]
}

I send data as props at the end, I am trying to display images like this:

<img src={props.item.image} alt={`${props.item.tokenId} image`} />

but I see nothing but in the DOM I see this:

<img src="../assets/images/collection/425.png" alt="425 image">

How can I fix this?

2

Answers


  1. I suspect it’s because you are passing a string path value that is processed at runtime when the page content is accessed instead of at build-time. In other words, the path URL is accessed when the app is running and the browser tries to fetch the image asset from the public directory.

    Use require(props.item.image) to attached the image asset correctly when building the component.

    <img
      src={require(props.item.image)}
      alt={`${props.item.tokenId} image`}
    />
    
    Login or Signup to reply.
  2. You need to import the images like below, so they are processed by the compiler (Webpack, I assume if you used create-react-app):

    import image23 from "../assets/images/collection/23.png";
    import image422 from "../assets/images/collection/23.png";
    const data = {
      lists: [
        {
          image: image23,
        },
        {
          image: image422,
        },
      ],
    };
    

    Or, move assets inside the public folder and use an absolute path, like so:

    const data = {
      lists: [
        {
          image: "/assets/images/collection/23.png",
        },
        {
          image: "/assets/images/collection/422.png",
        },
      ],
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search