'how to make next.js load images from public source with default img element
I have an SVG image I want to render through the classic JSX Element <img>, in place of the <Image>.
<img
src="/public/smiley-face.svg"
css={classes.sideSmileyFace}
alt="Presentation logo"
role="presentation"
/>
This way, the IDE does not complain about the position of my SVG file, but it's not rendered: the compilation does not transform that path into the correct one. On the other hand, if I place src="smiley-face.svg it does work, but the IDE complains. Any idea to fix this?
Solution 1:[1]
Files in the local public directory end up being served from "root" (https://whatever/) after compilation.
For regular <img />, either src="smiley-face.svg" or src="/smiley-face.svg" will work, with or without the leading slash (but don't include the word "public").
Next's custom <Image /> component on the other hand requires a leading slash since your image is relative (i.e., inside public). So only src="/smiley-face.svg" will work.
As for your IDE complaining, I'm guessing you're talking about a message that looks something like this?
Do not use
<img>. Use Image from 'next/image' instead.
If so, you can turn that message off by setting that rule to "off" in your .eslintrc.json file:
{
"extends": ["next/core-web-vitals"], // or whatever existing settings you have
"rules": {
"@next/next/no-img-element": "off" // add this
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mark G |
