How to display array of images from Sanity in Next.js slug page

7 replies
Last updated: Jan 28, 2026
i have an array of images for each post, trying to loop through them on a nextjs [slug] file and see the slug, but cannot figure out how to get the images to display.
AI Update

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:

  1. Changed urlFor(backgroundImage) to urlFor(background) - this passes the individual image object instead of the entire array
  2. Added a key prop using background._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-url helper expects a single image object, not an array
  • By passing background (the current item in the loop), you're giving urlFor() 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.

Show original thread
7 replies

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.

Was this answer helpful?