🎤 Builder Talk: The Story Behind Lady Gaga’s Digital Experience – Register now

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.
Jun 16, 2022, 1:52 AM
  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'
        }]
      }
    ],
  }])

Jun 16, 2022, 1:52 AM
[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

Jun 16, 2022, 1:53 AM
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[]->,
}
Jun 16, 2022, 2:31 AM
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?
Jun 16, 2022, 3:55 PM
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
    }
  }
}

Jun 16, 2022, 3:56 PM
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>
  )
}

Jun 16, 2022, 3:56 PM
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?
Jun 16, 2022, 4:40 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?

Related answers

Get more help in the community Slack

TopicCategoriesFeaturedRepliesLast Updated
Hey all - what’s the quickest way to batch delete all documents of a certain type? It looks like the `sanity` cli tool allows...Jan 29, 2021
Rendering nested block contentJan 18, 2021
In the tutorial, there is samples of what the API returns as JSON. Is there a way to view these ?Jan 11, 2021
Warning: Data for Page Exceeds the Threshold of 128 kBAug 17, 2022
Custom Document Views - Is it Even Possible to Use the Structure Builder?Apr 21, 2022
How to get the number of nested/children components in a GROQ query.Jan 19, 2024
Issue with fetching data from an array of references and non-references in a groq query.Dec 14, 2023
GraphQL query resolving references on a _raw field in GatsbyMay 17, 2022
GROQ query for getting references from arrays in another array in Sanity.ioApr 9, 2020
How to populate a list of values in a Sanity schema using a separate fileSep 6, 2021

Related contributions

Turbo Start Sanity
- Template

The battle-tested Sanity template that powers Roboto Studio's websites

Go to Turbo Start Sanity

Schema UI - Next.js Sanity Starter
- Template

A Next.js starter template with Next.js 15, Tailwind CSS, shadcn/ui, and Sanity CMS with Live Editing. Get production-ready React components with matching Sanity schemas and queries. Build dynamic pages faster while keeping full control over customization.

Serge Ovcharenko
Go to Schema UI - Next.js Sanity Starter

The Swaddle
- Made with Sanity

A new brand identity to represent a more mature company, to signify The Swaddle’s evolution from publisher to production house, combined with an easier to navigate platform that can surface multiple content types - drawing readers through The Swaddle’s content offering.

Nightjar
Go to The Swaddle