Next.js - How to Loop through an Array of Images on a [Slug] File
Based on the information I found, the issue is that you're passing the entire backgroundImage array to urlFor() instead of passing each individual image item. Here's how to fix it:
The problem is in this line:
{backgroundImage.map((background) => (
<img src={`${urlFor(backgroundImage).width(2000).auto("format").url()}`} />
))}You're mapping over backgroundImage and creating a background variable for each item, but then you're still passing the entire backgroundImage array to urlFor(). You need to pass the individual background item instead:
{backgroundImage.map((background) => (
<img
key={background._key}
src={`${urlFor(background).width(2000).auto("format").url()}`}
/>
))}Key changes:
- Changed
urlFor(backgroundImage)tourlFor(background)- this passes the individual image object instead of the entire array - Added a
keyprop usingbackground._key- React requires unique keys when rendering lists
This pattern works because:
- Each image object in your array has the structure
{_key: "...", _type: "image", asset: {...}} - The
@sanity/image-urlhelper expects a single image object, not an array - By passing
background(the current item in the loop), you're givingurlFor()the individual image it needs to generate the proper URL
If you're using Next.js's Image component for better performance, you can also do:
import Image from 'next/image'
import { urlFor } from './your-sanity-config'
{backgroundImage.map((background) => (
<Image
key={background._key}
src={urlFor(background).width(2000).url()}
alt="Background image"
width={2000}
height={1000} // adjust as needed
/>
))}This approach combines Sanity's Image Pipeline transformations with Next.js's image optimization for the best loading performance.
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.