aysam
aysam

Reputation: 25

Importing images dynamically from JSON file in reactJS

My json file: (items.json)

[
    {
        "title": "Nike shoes",
        "description": "New nike shoes",
        "price": "40$",
        "image": "../../../../assets/items/nike.jpg",
        "rank": "2"
    }
]

The file I'm trying to import the image in:

import React from "react";
import "./style.css";
import Items from "../../../../items.json";

export default function ListedItems() {
  return (
    <div>
      <div class="container">
        {Items.map(item => (
          <div class="col-sm-4">
            <div class="panel panel-primary">
              <div class="panel-heading">{item.title}</div>
              <div class="panel-body">
              <img
                  src={require(item.image)}
                  alt="Nike image"
                />
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

I get this error "Error: Cannot find module '../../../../assets/items/nike.jpg'" , if I use src={require('../../../../assets/items/nike.jpg')} it works.

Upvotes: 1

Views: 1900

Answers (1)

Andrii Golubenko
Andrii Golubenko

Reputation: 5179

The problem is that you try to import your images in a runtime. You wrote, that you used src={require('../../../../assets/items/nike.jpg')} and it worked. But this code doesn't work.

Yes, you won't have an error in a browser console, but the image also won't load. Because require() function returns a Promise. And in this case, you will have in your browser:

<img src="[object Promise]" alt="Nike image">
  1. You can resolve this issue by changing your items.json file from json to js and import images there.
import NikeImage from "../../../../assets/items/nike.jpg";
export const items = [
    {
        "title": "Nike shoes",
        "description": "New nike shoes",
        "price": "40$",
        "image": NikeImage,
        "rank": "2"
    }
]

and make some changes in your component:

<img src={item.image} alt="Nike image" />

But this code will only work if you are using file-loader in your webpack configuration.

  1. In case when you have to use only json files or you get this information from the server. You should use CopyWebpackPlugin. If you use create-react-app (as you wrote in a comment), it already contains CopyWebpackPlugin and it copies your public folder. In this case just move your assets folder to public and change your items.json file
...
"price": "40$",
"image": "/assets/items/nike.jpg",
...

and your component:

<img src={item.image} alt="Nike image" />

Upvotes: 3

Related Questions