How to reference and display objects from a certain field in Sanity.io

10 replies
Last updated: Aug 3, 2020
Is it possible to reference another document and then once it's selected, display a list of objects from a certain field to create a "sub-reference" for lack of a better term? For example, let's say I have two schemas (Case Study and Photo Gallery). I want to be able to create a new case study and reference the photo gallery. In addition, I'd like to select a photo from the photo gallery to use as the Hero Photo for the Case Study.
Aug 3, 2020, 12:04 PM
I think we have similar conundrum, I am trying to do similar thing but for product categories, I've added my schema with my question :). Hopefully someone knows how to get this done.
Aug 3, 2020, 12:27 PM
🤞
Aug 3, 2020, 12:27 PM
user L
do you mean something like the attached video?
Aug 3, 2020, 12:37 PM
Precisely that!
Aug 3, 2020, 12:38 PM
How did you pull that off? Anything you can share?
Aug 3, 2020, 12:41 PM
Sorry, just got pulled away for a sec!
Of course, give me a moment to see if I can simplify my example
Aug 3, 2020, 12:43 PM
🥳
Aug 3, 2020, 12:44 PM
Something’s come up and I can’t create a minimal example or clean this up, sorry! But hopefully this puts you on the right path:
https://gist.github.com/robinpyon/451521bbe88dc35c6cddd4a1044f80cb
Basically, the tldr is:
- you’ll need a custom input component
- this custom input needs to use
withDocument
HOC to be able to get the value for your selected photo gallery reference- it’s not pretty, but you can query the DOM to get the selected reference key
- with this key and the
withDocument
HOC, you can grab that photo gallery reference- use Sanity’s
client
library / helper to fetch the initial value on mount, and create a listener to grab updates in real time, making sure to unsubscribe on unmount
Aug 3, 2020, 1:07 PM
This is awesome, thanks for sharing. I will give it a shot!
Aug 3, 2020, 1:46 PM
Thanks
user G
looks like i can solve my problem with this approach as well 🙂.
Aug 3, 2020, 7:33 PM

Sanity– build remarkable experiences at scale

The Sanity Composable Content Cloud is the headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?

Categorized in