Easy way to display a Sanity Image asset in Studio preview.
22 replies
Last updated: Nov 12, 2021
E
Whats the easy way to show a Sanity Image asset -- i keep running into roadblocks.
Nov 12, 2021, 6:48 PM
E
More specifically, as a preview in the Studio.
Nov 12, 2021, 6:49 PM
E
I just want to take a "image" which is a reference (Sanity.imageAsset I believe) and show it.
Nov 12, 2021, 6:49 PM
E
It seems I have to create a client, then use the
@sanity/image-urlto build the url to show the image?
Nov 12, 2021, 6:50 PM
E
Acutally, I just realized I select the asset url right in the "select" with nested notation.
Nov 12, 2021, 6:52 PM
In what context do you want show it? Would it be within a document or in a separate preview pane? I guess, to put it more simply, what's the ultimate goal of displaying it?
Nov 12, 2021, 6:53 PM
E
Just a thumbnail preview on the document list.
Nov 12, 2021, 6:53 PM
E
... preview: { select: { title: 'title', mainImage: 'mainImage.asset.url', }, prepare(selection) { return { title: selection.title, media: <img src={`${selection.mainImage}`} />, }; }, }, ...
Nov 12, 2021, 6:54 PM
E
That actually works -- but I'm not sure how I can get a smaller scaled and cropped version of "mainImage".
Nov 12, 2021, 6:54 PM
E
Thats in a document schema
Nov 12, 2021, 6:55 PM
Got it. You should just be able to select the field and display it. Like this:
preview: { select: { title: 'title', media: 'mainImage', } }
Nov 12, 2021, 7:01 PM
E
So in that case
mediaseems to be returning just
{ asset: { _type: "reference", _ref: "..." } }
Nov 12, 2021, 7:02 PM
E
So in that case
mediaseems to be returning just
{ asset: { _type: "reference", _ref: "..." } }
Nov 12, 2021, 7:02 PM
E
{ title: 'Main Image', name: 'mainImage', type: 'image', options: { hotspot: true, }, },
Nov 12, 2021, 7:03 PM
E
So in that case
mediaseems to be returning just
{ asset: { _type: "reference", _ref: "..." } }
Nov 12, 2021, 7:02 PM
That should be setting the icon of the item in the document list to the image in that schema. When you say returning, where is it returning?
Nov 12, 2021, 7:05 PM
E
Oh...
Nov 12, 2021, 7:06 PM
E
Wow -- that worked out very nicely haha
Nov 12, 2021, 7:07 PM
E
I was way over thinking that apparently.
Nov 12, 2021, 7:07 PM
E
I feel like that was magic I never knew about
Nov 12, 2021, 7:07 PM
It happens! If you're not doing any sort of transformations or calculations, etc., it's surprisingly easy to set up the previews.
Nov 12, 2021, 7:07 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.