I have several hundreds of images for a dynamically growing image gallery build with nextjs. Images are inside the public folder and can be shown with
import image1 from '../../public/image1.png'
// this works
<img src={image1.src} />
How can I dynamically show images without creating an import for each of the images up front like so?
// doesnt work
let imgId = 5
<img src=`../../public/image${imgId}.png` />
I also tried the built in Image
component like so but without luck:
// doesnt work
<Image
src={"/image/" + imgId + ".png"}
height="100"
width="100"
alt="image"
/>
Also the solution with require.context()
will not work as nextjs does not use webpack.
2
Answers
Based on this answer from here my solution is using an api:
Create a file named
[image].ts
within thepublic/api/
folderAnything in public directory should be accessible with absolute path.
If there is an "image.jpg" in /public directory it should be accessible with https://yourdomain/image.jpg.