Next.js - How to Loop through an Array of Images on a [Slug] File

7 replies
Last updated: Jun 16, 2022
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.

  types: schemaTypes.concat([{
    name: 'post',
    type: 'document',
    title: 'Post',
    fields: [
      {
        title: 'Slug',
        name: 'slug',
        type: 'slug'
      },
      {
        title: 'Name',
        name: 'name',
        type: 'string'
      },
      {
        name: 'images',
        type: 'array', // supports drag'n'drop of multiple files
        options: {
          layout: 'grid'
        },
        of: [{
          type: 'image'
        }]
      }
    ],
  }])

[slug].js
// [slug].js

import client from '../../client'

const Post = (props) => {
  const { name = 'Missing title', slug = 'missing slug', images = 'Missing images' } = <http://props.post|props.post>
  return (
    <article>
      <h1>{name}</h1>
      <span>By {images}</span>

      {posts.categories.map((category) => (
    <li key={category}>
      <span>
        {category}
      </span>
    </li>
  ));
}

    </article>
  )
}

export async function getStaticPaths() {
  const paths = await client.fetch(
    `*[_type == "post" && defined(slug.current)][].slug.current`
  )

  return {
    paths: paths.map((slug) => ({params: {slug}})),
    fallback: true,
  }
}

export async function getStaticProps(context) {
  // It's important to default the slug so that it doesn't return "undefined"
  const { slug = "" } = context.params
  const post = await client.fetch(`
    *[_type == "post" && slug.current == $slug][0]{name, "images": author->name}
  `, { slug })
  return {
    props: {
      post
    }
  }
}

export default Post

Hey
user K
! You'll want to loop through your array with
[]
, then expand the image asset ref with
->
. All told, it looks like this:
*[_type == "post" && slug.current == $slug][0]{
  name,
  images[]->,
}
thanks for helping, i’m still getting no results for images, i created another test field and that’s returning fine. is there an example of looping through the images that you’d recommend?
export async function getStaticProps(context) {
  // It's important to default the slug so that it doesn't return "undefined"
  const { slug = "" } = context.params
  const post = await client.fetch(`
    *[_type == "post" && slug.current == $slug][0]{
      name,
      tester,
      images[]->,
    }
  `, { slug })
  return {
    props: {
      post
    }
  }
}

const Post = (props) => {
  const { name = 'Missing title', tester = 'missing test....', images = 'Missing images' } = <http://props.post|props.post>
  return (
    <article>
      <h1>{name}</h1>
      <span>By {images}</span>
      <span>{tester}</span>
    </article>
  )
}

Yes! Documentation and examples: here , here , and here . The images are going to be returned as objects, so your current syntax will throw an error. Also, does the document you're accessing have images added and is it published?

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?