skip to Main Content

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


  1. 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 in src.

    To avoid that, you can consider using the public folder for your images, this way, you can put your absolute path inside src.

    You can also add folders inside public folder (i.e. assets and inside it images) then to reference it:

    <img src="/assets/images/img1.jpg" alt="img1" className="h-full" />
    

    Notice that the path starts with /, indicating that it’s an absolute path from the root of the public folder.

    Login or Signup to reply.
  2. This is because ../assets/images/img1.jpg is localhost: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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search