I am making a ReactJs website and when I try to add image to my website using img
tag, it does not work when I specify the path of the image in the src
attribute of the img
tag but works when I first import the image using import
and add that variable in src
.
import React from "react";
import imagePath from '../assets/images/img1.jpg'
function ImageSlider() {
return (
<section className="bg-red-300 h-full ">
Does work
<img src={imagePath} alt="img1" className="h-full" />
Does not work
<img src="../assets/images/img1.jpg" alt="img1" className="h-full" />
</section>
)
}
export default ImageSlider;
2
Answers
That’s because of how the bundler (whether it’s Webpack or Vite) works.
When you use
import
, the bundler includes the image in the build process correctly. However, that’s not the case when you directly place the url insrc
.To avoid that, you can consider using the
public
folder for your images, this way, you can put your absolute path insidesrc
.You can also add folders inside
public
folder (i.e.assets
and inside itimages
) then to reference it:Notice that the path starts with
/
, indicating that it’s an absolute path from the root of thepublic
folder.This is because
../assets/images/img1.jpg
islocalhost:5000/..../assets/images/img1.jpg
.In
import imagePath from '../assets/images/img1.jpg'
the image is imported from the file eg.
D:/projectname/public/assets/images/img1.jpg