👋 Next.js Conf 2024: Come build, party, run, and connect with us! See all events

Using conditional fields to set up an object with multiple types in Sanity.io.

2 replies
Last updated: Jan 10, 2024
Hey everyone! I started working with Sanity a few days ago and I love it! Had a quick question: You can currently set a field with type
array
to include multiple types using
of: [type1, type2, etc.]
which can allow you to choose from a variety of types in that array. Is there a way to do something similar, but with one
object
instead of an array? I want to have a
object
that can be one of several types. For example, something similar to
{name: 'Lead', type: 'object', of: [{type: 'heroLead'}, {type: 'basicLead'}]}
for a
lead
field in a page document. I can currently use an array with a max-length of 1, but was wondering if there was a cleaner approach to doing this
Jan 9, 2024, 8:49 PM
👋 The closest you can get to this is using conditional fields . You’d need to set up a select field with the different types as options, then show and hide fields using the
hidden
callback.
Jan 10, 2024, 1:15 AM
Makes sense, thank you!
Jan 10, 2024, 4:00 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.

Was this answer helpful?