πŸ‘€ See Sanity in action: Watch product demo now β†’

Nextjs - How to Display Objects With Nextjs

14 replies
Last updated: Jun 6, 2022
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):


{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
Is
@sanity/image-url
the 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
so something like this? whereby
Parternaires
is 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
this is the schema πŸ™‚
Jun 6, 2022, 8:44 PM
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
This is my output with that config:
Jun 6, 2022, 8:50 PM
this is when i log the output of
Partneraires
Jun 6, 2022, 8:50 PM
Oh I got it! I had to change
image
in 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
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
thanks for ur help!!
Jun 6, 2022, 8:59 PM
Glad we got it sorted out!
Jun 6, 2022, 9:01 PM

Sanity.io – build remarkable experiences at scale

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