Nextjs - How to Display Objects With Nextjs
14 replies
Last updated: Jun 6, 2022
A
Hi all, follow-up question to the one I asked earlier; I'm wondering what the best way to go about displaying my images with Nextjs is.
In my case, I'm rendering an object array with a name and an image, but I'm struggling to display the image properly (next Image fails to parse the src):
In my case, I'm rendering an object array with a name and an image, but I'm struggling to display the image properly (next Image fails to parse the src):
{logos[0].Partenaires.map((partner, i) => ( <Image src={partner.partnerLogo.asset._ref} alt={partner.partnershipName} key={i} height={40} quality={100} layout="fill" /> ))}
Jun 6, 2022, 8:27 PM
A
Is
@sanity/image-urlthe only way to get a url from these images?
Jun 6, 2022, 8:34 PM
You can also get the url by expanding the asset reference in your query using
->.
Jun 6, 2022, 8:37 PM
A
so something like this? whereby
Parternairesis my object array
*[_type=="informationsGenerales"]{ Partenaires[] { ..., _type == "image => { "image": asset->url } }, "image": image.asset->url }
Jun 6, 2022, 8:40 PM
What does your schema look like? If the object in the array is always going to have an image you may be able to skip the conditional!
Jun 6, 2022, 8:43 PM
A
this is the schema š
Jun 6, 2022, 8:44 PM
A
I'm ok to skip the string field on line 22 if there's a way to attach an alt to the image coming out of Sanity
Jun 6, 2022, 8:45 PM
You can't attach an alt or anything like that in an out of the box image, but I think you can with the Media Plugin . It looks like we can drop that conditional and go with a named field. The following should get you the url:
*[_type=="informationsGenerales"]{ Partenaires[] { ..., "imageUrl":image.asset->url }, }
Jun 6, 2022, 8:48 PM
A
This is my output with that config:
Jun 6, 2022, 8:50 PM
A
this is when i log the output of
Partneraires
Jun 6, 2022, 8:50 PM
A
Oh I got it! I had to change
imagein the query to
partnerLogo(what I named it in the schema).
Jun 6, 2022, 8:54 PM
AH, yeah, I was just looking at the top line of your schema and assumed that was the name. My own schema practices created selective blindness š
Jun 6, 2022, 8:57 PM
A
no problem lol, i'm still new to writing these queries so I assumed image.asset was some sort of keyword š¤£
Jun 6, 2022, 8:59 PM
A
thanks for ur help!!
Jun 6, 2022, 8:59 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.