javascriptreactjsvite

Why wont my images load in my React Vite project?


Public Folder>> leaves.jpg

App.jsx:

function App() {
return (
<img src="./public/leaves.jpg" alt "img" />
)
}

The image is showing up on my image-preview extension which usually indicated the path is correct, I'm not sure what I'm doing wrong. It doesn't return an error when I try to use this method. I also tried importing the image like: import leaves from './public/leaves.jpg' and plugging it in like: <img src={leaves} alt "img" />, but it was throwing an error that the file couldn't be found.

Any help would be appreciated, thank you.


Solution

  • The public folder gets served from the root (/), so you need just:

    <img src="/leaves.jpg" alt "img" />
    

    See docs:

    You should always reference public assets using root absolute path - for example, public/icon.png should be referenced in source code as /icon.png.