Home > Software engineering >  Why does the <img> source path works only for import and url?
Why does the <img> source path works only for import and url?

Time:08-01

I am trying to create a simple react site. But in the process of creating it, I have encountered this issue with <img src="./logo.png"></img>.

Situation

  • Image loads normally when I use image URL or I use import LOGO from "./logo.png" But when I use <img src="./logo.png" alt=sample-image></img>, my image doesn't load and alt text appears.

Please help to understand why is it happening. Here is my full code of JS file-

import ReactDOM from "react-dom/client"
import LOGO from "./logo.png"
const divElement = (
    <div>
        <img src={LOGO} alt="react-logo" width="40px"></img>
        <h1>Fun Facts About React</h1>
        <ul>
            <li>Was first released in 2013</li>
            <li>Was originally created by Jordan Walke</li>
            <li>Has well over 100K stars on Github</li>
            <li>Is maintained by Facebook</li>
            <li>Powers thousands of enterprise apps, including mobile apps</li>
        </ul>
    </div>
)
ReactDOM.createRoot(document.getElementById("root")).render(divElement)

CodePudding user response:

If you created the project with vite or CRA, you need to put your image in the public folder and then your path would be :

<img src="/logo.png" alt="sample-image" />

  • Related