Undefined slug.current and post.image when querying referenced vs referencing images
Looking at your gist, I can see the issue! In [slug-1].js (the collection page), you're mapping over post.images but then trying to render post.slug.current and post.image outside the map function. The problem is that post in that context refers to your collection document, not the individual image documents.
Here's what's happening:
In your working [slug].js (camera page):
{post.photos.map((post) => {
// Here 'post' is each individual photo document
return (
<Link href={`/photo/${encodeURIComponent(post.slug.current)}`}>
<Image src={urlFor(post.image).auto('format').url()} />
</Link>
)
})}In your broken [slug-1].js (collection page):
{post.images.map((post) => {
console.log(post.image)
})}
// This div is OUTSIDE the map - 'post' here is still the collection!
<div>
<Link href={`/photo/${encodeURIComponent(post.slug.current)}`}>
<Image src={urlFor(post.image).auto('format').url()} />
</Link>
</div>The fix: Move your JSX inside the map function and return it, just like in your camera page:
{post.images.map((image) => { // Rename to 'image' to avoid confusion
return (
<div sx={{
'> a > div': {
position: 'relative !important',
height: 'auto',
display: 'block',
aspectRatio: '1 / 1',
},
'> a > div > img': {
height: '100% !important',
width: '100% !important',
position: 'relative !important',
}
}}>
<Link href={`/photo/${encodeURIComponent(image.slug.current)}`}>
<a>
<Image src={urlFor(image.image).auto('format').url()} layout="fill" objectFit="cover" />
</a>
</Link>
</div>
)
})}The key changes:
- Added
returnstatement inside the map - Renamed the parameter from
posttoimageto avoid confusion with the outerpostvariable - Moved all the JSX inside the map function so it renders for each image
Your GROQ query looks correct - it's dereferencing the image references properly with "images": images[]->{image, slug}. The issue was purely in how you were rendering the data in React!
Show original thread15 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.