How to Create an Array of Blocks

1 replies
Last updated: Jun 27, 2022
Hi folks!Can I create an array of blocks?
AI Update

Yes, you can absolutely create an array of blocks in Sanity! This is actually one of the core features of Sanity's content modeling.

When you define a field as an array containing block types, you're creating what's commonly called "Block Content" or Portable Text. This allows you to mix rich text paragraphs with custom content types like images, videos, code blocks, and any custom components you create.

Here's a basic example of how to define an array of blocks in your schema:

defineField({
  name: 'body',
  type: 'array',
  of: [
    {type: 'block'}, // Standard rich text block
    {type: 'image'}, // Image block
    // Add any custom block types you want
  ]
})

The {type: 'block'} gives you the standard rich text editor with formatting options like bold, italic, headings, and lists. You can then add other block types to the array - either built-in types like image or your own custom blocks.

The beauty of this approach is that content creators can mix and match different block types within a single field, creating rich, modular content. Each block in the array is an independent object with its own structure, making your content both flexible and structured at the same time.

This is different from traditional HTML-based rich text editors because your content is stored as structured JSON data, making it portable across different platforms (web, mobile, voice assistants, etc.) and easier to work with programmatically. You can learn more about configuring the Portable Text editor to customize exactly which formatting options and block types are available to your content editors.

The
block
type already has to be within an array, and you can’t have an array of arrays in Sanity. Instead you could wrap the
block
in an object and put this inside of an array, as follows:
blockObject.js

export default {
    title: "Block",
    name: "blockObject",
    type: "object",
    fields: [
        {
            title: "Block Text",
            name: "blockText",
            type: "array",
            of: [{ type: "block" }],
        },
    ],
};
exampleDocument.js

export default {
    name: "Example Document",
    title: "exampleDocument",
    type: "document",
    fields: [
        {
            title: "Block Array",
            name: "blockArray",
            type: "array",
            of: [{ type: "blockObject" }],
        },
    ],
};

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?