Search code examples
jsonreactjs

React, load images local from json


Yes, this question may be duplicated from other questions, but I couldn't find solution for this problem.

I create something simple

1 component that read a json and load image.

The json

{
  "images": [
    {
      "id": 1,
      "url": "../assets/images/slider/croissant-other.jpg",
      "description": "Croissant"
    },
    {
      "id": 2,
      "url": "../assets/images/slider/croissant-3570.jpg",
      "description": "Croissant 3570"
    }
  ]
}

The component

import React from "react";
import jsonCarrousel from "../data/carrousel.json";

function Carrousel() {
  return (
    <div>
      {jsonCarrousel.images.map((image, i) => (
        <div className="item" key={i}>
          <img src={require(`${image.url}`)} alt={image.description} key={i} />
        </div>
      ))}
    </div>
  );
}

export default Carrousel;

The example in live

https://codesandbox.io/s/stupefied-fast-1zfdj

The error:

/src/assets/images/slider/croissant-other.jpg hasn't been transpiled yet.

Solution

  • Compiled code will look into /public to find your images. You should move your assets to /public instead of src. (manually or by bundle tool)

    Also, image source should be src={`${image.url}`}

    https://codesandbox.io/embed/elastic-solomon-1ul1o