Search code examples
reactjs

How to assign image src dynamically without import or component in react


I need assistance of displaying the images without import or any external component. I have tried all the below methods but nothing worked out. Any assistance on this matter is much appreciated.

When i use require(), I get the error a Cannot find module '../assets/images/products

import React from "react";
    
export default function ProductGallery() {
  const products = [
    {
      ProductImage: "../assets/images/products/image1.jpg",
    },
    {
      ProductImage: "../assets/images/products/image2.jpg",
    },
  ];

  return (
    <div className="row">
      {products.map((item, index) => (
        <div className="galleryBox" key={index}>
          <img src={require(item.ProductImage)}/>
          <img src={require(""+item.ProductImage)}/>
          <img src={require(`${item.ProductImage}`)}/>
          // all the three methods didnt work
          <img src={item.ProductImage}/>
          // this doesnt show image at all. When I Inspect, it shows the path correct. But it should come from ../static, however it showing actual path
        </div>
      ))}
    <div>
  );
}

Solution

  • Place the image in the Public folder, so that, the reference path can pull the image.