Undefined slug.current and post.image when querying referenced vs referencing images
I’ve successfully been able to reference the images I’m looking for, but I’m unable to use them in my front end for some reason! The only difference between this page and another is how I’m querying the images - in this gist, [slug].js is querying all image documents that reference this document (camera), and in [slug-1].js I’m querying a list of images that this document (collection) references.
There must be something I’m missing in how I process these queries and join the data, because next is giving me undefined for slug.current and post.image! Can anyone help?
https://gist.github.com/jenkshields/ec7a11fe3b0f830c40276c4343d33620
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
Was this answer helpful?
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.