Is it possible to have a drop down that present a choice between two different types? Like a string and an image? Would it need to be an array?

2 replies
Last updated: Feb 3, 2021
Is it possible to have a drop down that present a choice between two different types? Like a string and an image? Would it need to be an array?
AI Update

Based on the documentation, yes, you can have a field that allows choosing between different types (like a string and an image), and you would use an array field to accomplish this.

Here's how it works:

Array fields in Sanity can contain multiple member types within the same array using the of property. You define each possible type as an object in the array, and the Studio will present a dropdown/menu when adding new items that lets the user choose which type to add.

Here's an example combining strings and images:

{
  name: 'flexibleContent',
  title: 'Flexible Content',
  type: 'array',
  of: [
    {
      type: 'object',
      name: 'textItem',
      title: 'Text',
      fields: [
        {
          name: 'text',
          type: 'string'
        }
      ]
    },
    {
      type: 'image',
      name: 'imageItem',
      title: 'Image'
    }
  ]
}

When editors interact with this field in the Studio, they'll see an "Add item" button that opens a dropdown menu showing "Text" and "Image" as options. They can choose which type to add, and the array can contain a mix of both types.

Important notes:

  1. Even if you only want a single item (not multiple), you'd still use an array field - you can just add validation to limit it to one item: validation: Rule => Rule.max(1)

  2. If you're using GraphQL, avoid anonymous inline objects and instead define named object types at the top level of your schema, as GraphQL requires top-level schema types for nested objects.

  3. Each item in the array automatically gets a unique _key property that Sanity uses to track items.

This pattern is commonly used for flexible content structures where editors need to mix different content types in a single field.

Show original thread
2 replies
Yeah, I use arrays when I need to do this. You can create the types, and then reference them.
I see, thanks.

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?