Unlock seamless workflows and faster delivery with our latest releases – get the details

The Power of Polymorphic Arrays

Polymorphic arrays are a great way to structure serialized content. Learn how Sanity gives you one of the most powerful examples of this with instant UIs for editors.

Published

  • Knut Melvær

    Knut Melvær

    Head of Developer Community and Education

Clothingline

You probably don't realize this (and we don't blame you), but you are now looking at a polymorphic array. Or in simpler terms, an array of different content types. Sanity is not unique in having these, you find them in many CMSs under many names: matrix, repeater, blocks, replicator. We just called the type array, because that is what it is.

There are many reasons polymorphic arrays are useful. A typical example is using them to make page builders, as we have done in the Next.js Landing Page example:

export default {
  name: 'content',
  type: 'array',
  title: 'Page sections',
  of: [
    { type: 'hero' },
    { type: 'imageSection' },
    { type: 'mailchimp' },
    { type: 'textSection' },
  ]
}

This is where Sanity shines. Those types are custom object types that can be reused across your project. So if you need a hero (a backgroud image and a title) another place you can add a { type: 'hero' } and off you go. Those custom types can also contain their own polymorphic arrays, and so on. The best thing is: When you define these content models in these simple JavaScript objects, you'll also get the editor UI instantly generated.

The schema definition above produces this input field in Sanity Studio:

An array field with an add button and a menu of different types to insert
The page builder

You can also customize how these array items should be previewed in this context, even with your own custom React components.

A more interesting case is what we use them for: rich text content, where you can have different data objects both in blocks, and inline spans. Instead of locking your content to HTML (which is super cool in browsers, but kinda of a hassle elsewhere), it is structured in objects inside of an JSON array. This way of dealing with rich text content is formalized in the specification called Portable Text (portabletext.org).