Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I load multiple images with Next Image from a loop?

I have:


const TEMPLATE_TYPES = [
    {
        name: 'Blog Post',
        type: 'blog-post',
        img: '/img1.png'
    },...
];

Later, I have a loop over TEMPLATE_TYPES:

{templateType.img && <img src={templateType.img} />}

But I want to convert this to Next.js's <Image /> tag. How would I accomplish this?

Thanks!

like image 901
Shamoon Avatar asked Nov 15 '25 12:11

Shamoon


1 Answers

From the nextJs docs:

Next.js can serve static files, like images, under a folder called public in the root directory. Files inside public can then be referenced by your code starting from the base URL (/).

as long as your images are in the public folder you don't have to import them, so just keep as it is.

// TEMPLATE_TYPES
img: '/img1.png'

but keep in mind that:

Note: Only assets that are in the public directory at build time will be served by Next.js. Files added at runtime won't be available. We recommend using a third party service like AWS S3 for persistent file storage.

See the docs about serving static content for more info.

Another thing, in the future maybe you will want to access files from a remote domain, like aws bucket, in such case you have to add the domain on the next.config.js like so:

// next.config.js file
module.exports = {
  images: {
    domains: ['example.com', 'example2.com'],
  },
}

for more info take a look here

and finally, you can create a component that gets the object and render your images:

const RenderImage = (props) => {
  const images = props.images;
  return (
    <>
      {images.map((img, i) => (
        <div key={i}>
          <h4>{img.name}</h4>
          <Image src={img.img} width={500} height={300} />
        </div>
      ))}
    </>
  );
};

//Later somewhere on your code:
<RenderImage images={TEMPLATE_TYPES} />

The code above is just an example, but i think you got the idea, see also the api docs about the image component. Hope i helped a bit!

like image 110
Yago Biermann Avatar answered Nov 18 '25 19:11

Yago Biermann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!