0

guys! I have object with images. I need to go through the object and render images from there. (I will have plenty of them). Here is my js file:

const myJson = {
    "data": [
      {
        "id": 1,
        "name": "Landscape of Saint-Remy",
        "path": "./a.jpg",
        "cost": 400,
      },
      {
        "id": 2,
        "name": "Landscape of Saint-Remy",
        "path": "./b.jpg",
        "cost": 400,
      },
      {
        "id": 3,
        "name": "Landscape of Saint-Remy",
        "path": "./c.jpg",
        "cost": 400,
      },
    ]
  }

export default myJson;

I try to render it in my Home component like this:

import React from 'react';
import myJson from '../../server/myJson';

function Home() {
        return (
             <div>
                 <Hi />
                {myJson.data.map(key => (
                  <img src={require(`${key.path}`)} key={key} />
                ))}
            </div>
         )

But got an error: Module can't be found.

If I render images like this:

<img src={key.path} key={key} />

I see 200ok, but no image because I need to import it and that is why I used require to import image and use it. But it's not working.

Please, help me!

Elina
  • 21
  • 4
  • Did you try to set width and heigh of the image ? Because a 200 ok means you've well received the image, just not displaying properly. – AymericFi Mar 22 '21 at 14:04

2 Answers2

0

This is not the way to import images, you need to config you webpack and add file-loader or url-loader to require images inside your javascript.

Take a look at this answer: https://stackoverflow.com/a/37673142/5497628

0

Here this is how you can do it

const myJson = {
"data": [
  {
    "id": 1,
    "name": "Landscape of Saint-Remy",
    "path": require("./a.jpg"),
    "cost": 400,
  },
  {
    "id": 2,
    "name": "Landscape of Saint-Remy",
    "path": require("./b.jpg"),
    "cost": 400,
  },
  {
    "id": 3,
    "name": "Landscape of Saint-Remy",
    "path": require("./c.jpg"),
    "cost": 400,
  },
]
}

export default myJson;

This is how you have to prepare json data.

import React from 'react';
import myJson from '../../server/myJson';

function Home() {
       return (
         <div>
             <Hi />
            {myJson.data.map(key => (
              <img src={key.path} key={key} />
            ))}
        </div>
     )

This is how you can render it.

  • Are you suggesting moving the `require` from the component file to the `myJson` file? I think the question asker did that. There really is no telling where the images actually are in this question. Plus there are tons of questions for `React` and relative image paths using [require](https://stackoverflow.com/questions/64910839/require-function-not-working-with-image-in-react) and [import](https://stackoverflow.com/questions/44154939/load-local-images-in-react-js). – treckstar Jul 10 '22 at 15:26