Watch a live product demo 👀 See how Sanity powers richer commerce experiences

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 (
    &lt;article&gt;
      &lt;h1&gt;{name}&lt;/h1&gt;
      &lt;span&gt;By {images}&lt;/span&gt;

      {posts.categories.map((category) =&gt; (
    &lt;li key={category}&gt;
      &lt;span&gt;
        {category}
      &lt;/span&gt;
    &lt;/li&gt;
  ));
}

    &lt;/article&gt;
  )
}

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

  return {
    paths: paths.map((slug) =&gt; ({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" &amp;&amp; slug.current == $slug][0]{name, "images": author-&gt;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
-&gt;
. All told, it looks like this:
*[_type == "post" &amp;&amp; slug.current == $slug][0]{
  name,
  images[]-&gt;,
}
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" &amp;&amp; slug.current == $slug][0]{
      name,
      tester,
      images[]-&gt;,
    }
  `, { slug })
  return {
    props: {
      post
    }
  }
}

Jun 16, 2022, 3:56 PM
const Post = (props) =&gt; {
  const { name = 'Missing title', tester = 'missing test....', images = 'Missing images' } = <http://props.post|props.post>
  return (
    &lt;article&gt;
      &lt;h1&gt;{name}&lt;/h1&gt;
      &lt;span&gt;By {images}&lt;/span&gt;
      &lt;span&gt;{tester}&lt;/span&gt;
    &lt;/article&gt;
  )
}

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

The Sanity Composable Content Cloud is the 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.

Categorized in

Related answers

Get more help in the community Slack

TopicCategoriesFeaturedRepliesLast Updated
After adding the subtitle and running this code npm run graphql-deploy It does nothingSep 15, 2020
how to limit a reference to just one entry in Studio reference input side versus the default as-many-entries-as-you-fill-in-an-array...Sep 18, 2020
Is it possible to fetch more than one "_type" using GROQ?Nov 2, 2020
I want to add a view with the Structure builder (S.view.component) where I list similar documents based on the title. What...Sep 23, 2020
Is there a structure builder example where the format of each preview for the document list is modified?Feb 3, 2021
I have an array of references to a country schema type but it always just returns NULL values for meJan 30, 2021
Hi, I need help with a query for getting the url of an image asset. Here is what I've been trying, but I only get the _ref...Dec 1, 2020
Sanity UI looks brilliant :smiley: Is something like the current date picker possible at the moment? I’m not sure if anicon...Dec 21, 2020
Hey everyone. I have been coding and may have potentially accidentally deleted something. Does anyone know how to resolve...Dec 26, 2020
Hello everyone and happy new year :raised_hands::skin-tone-2:, I have a problem with outputting Portable Text :disappointed:...Jan 1, 2021

Related contributions

Clean Next.js + Sanity app
- Template

Official(made by Sanity team)

A clean example of Next.js with embedded Sanity ready for recomposition.

Cody Olsen
Go to Clean Next.js + Sanity app

Blog with Built-in Content Editing
- Template

Official(made by Sanity team)

A Sanity-powered blog with built-in content editing and instant previews.

Go to Blog with Built-in Content Editing