1

I have created a js file where an array contains multiple objects. Every object has an image path given. Using for loop, I am importing every object to my component. Everything works fine except the image. It's broken. It's not taking the relative path. I have stored all the images in a folder. Below is my code:

Data.js

export const dashboardUtil = [
     {
       title: "Posts",
       count: 500,
       image: "/src/images/1.png"
     }
   //rest of the objects
]

Component.js

let blocks = [];

for(let i=0;i<dashboardUtil.length;i++){
    blocks.push(
            <Col xs={12} md={6} sm={6}>
              <div className="main-block" className="stats-block">
                <h3>{dashboardUtil[i].title}</h3>
                <p>{dashboardUtil[i].count}</p>
                <img src={dashboardUtil[i].image} />
              </div>
            </Col>
          );
}
Vinay Singh
  • 463
  • 2
  • 9
  • 16

2 Answers2

1
image: "/src/images/1.png"

This is not a relative path, its absolute (starts with slash). If you intend it to be relative, use ./ e.g. ./src/images/1.png.

The bigger issue is that you're providing a path to a local resource to the context of the users browser. It expects this to be a http(s):// resource. You need to provide an endpoint that your web server handles and serves up the resource.

Either:

  • Your image needs to go into a location your web server can access, and you need to set the img src attribute to reference that location
  • You should look into webpack and a file loader plugin that takes a local image path via require(), and copies that to an accessible location.
Dave Meehan
  • 3,133
  • 1
  • 17
  • 24
-1

use : import image from "../pathToImageFolder/image1.png";

//path to image will be automatically constructed by webpack

<img src={image}>

Chetan B B
  • 31
  • 1