Back to Payload

Blocks Field

docs/fields/blocks.mdx

3.84.127.5 KB
Original Source

The Blocks Field is one of the most flexible tools in Payload. It stores an array of objects, where each object is a “block” with its own schema. Unlike a simple array (where every item looks the same), blocks let you mix and match different content types in any order.

This makes Blocks perfect for building dynamic, editor-friendly experiences, such as:

  • A page builder with blocks like Quote, CallToAction, Slider, or Gallery.
  • A form builder with block types like Text, Select, or Checkbox.
  • An event agenda where each timeslot could be a Break, Presentation, or BreakoutSession. <LightDarkImage srcLight="https://payloadcms.com/images/docs/fields/blocks.png" srcDark="https://payloadcms.com/images/docs/fields/blocks-dark.png" alt="Admin Panel screenshot of add Blocks drawer view" caption="Admin Panel screenshot of add Blocks drawer view" />

To add a Blocks Field, set the type to blocks in your Field Config:

ts
import type { Field } from 'payload'

export const MyBlocksField: Field = {
  // ...
  // highlight-start
  type: 'blocks',
  blocks: [
    // ...
  ],
  // highlight-end
}

This page is divided into two parts: first, the settings of the Blocks Field, and then the settings of the blocks inside it.

Block Field

Block Config Options

OptionDescription
name *To be used as the property name when stored and retrieved from the database. More details.
labelText used as the heading in the Admin Panel or an object with keys for each language. Auto-generated from name if not defined.
blocks *Array of block configs to be made available to this field.
validateProvide a custom validation function that will be executed on both the Admin Panel and the backend. More details.
minRowsA number for the fewest allowed items during validation when a value is present.
maxRowsA number for the most allowed items during validation when a value is present.
saveToJWTIf this field is top-level and nested in a config supporting Authentication, include its data in the user JWT.
hooksProvide Field Hooks to control logic for this field. More details.
accessProvide Field Access Control to denote what users can see and do with this field's data. More details.
hiddenRestrict this field's visibility from all APIs entirely. Will still be saved to the database, but will not appear in any API response or the Admin Panel.
defaultValueProvide an array of block data to be used for this field's default value. More details.
localizedEnable localization for this field. Requires localization to be enabled in the Base config. If enabled, a separate, localized set of all data within this field will be kept, so there is no need to specify each nested field as localized.
uniqueEnforce that each entry in the Collection has a unique value for this field. This creates a database-level unique index on the field's path. More details.
labelsCustomize the block row labels appearing in the Admin dashboard.
adminAdmin-specific configuration. More details.
customExtension point for adding custom data (e.g. for plugins)
typescriptSchemaOverride field type generation with providing a JSON schema
virtualProvide true to disable field in the database, or provide a string path to link the field with a relationship. See Virtual Fields

* An asterisk denotes that a property is required.

<Banner type="warning"> Setting `unique: true` on a field **inside** a Block creates a collection-wide database unique index — not a per-document one. No two documents in the collection can share the same value at that nested path, and on MongoDB, documents without the block will collide on `null`. To enforce uniqueness within a single document's blocks, use a custom [`validate`](/docs/fields/overview#validation) function on this Blocks field. [More details](/docs/database/indexes#unique-fields). </Banner>

Block Admin Options

To customize the appearance and behavior of the Blocks Field in the Admin Panel, you can use the admin option:

ts
import type { Field } from 'payload'

export const MyBlocksField: Field = {
  // ...
  admin: {
    // highlight-line
    // ...
  },
}

The Blocks Field inherits all of the default admin options from the base Field Admin Config, plus the following additional options:

OptionDescription
initCollapsedSet the initial collapsed state
isSortableDisable order sorting by setting this value to false

Customizing the way your block is rendered in Lexical

If you're using this block within the Lexical editor, you can also customize how the block is rendered in the Lexical editor itself by specifying custom components.

  • admin.components.Label - pass a custom React component here to customize the way that the label is rendered for this block
  • admin.components.Block - pass a component here to completely override the way the block is rendered in Lexical with your own component

This is super handy if you'd like to present your editors with a very deliberate and nicely designed block "preview" right in your rich text.

For example, if you have a gallery block, you might want to actually render the gallery of images directly in your Lexical block. With the admin.components.Block property, you can do exactly that!

<Banner type="success"> **Tip:** If you customize the way your block is rendered in Lexical, you can import utility components to easily edit / remove your block - so that you don't have to build all of this yourself. </Banner>

To import these utility components for one of your custom blocks, you can import the following:

ts
import {
  // Edit block buttons (choose the one that corresponds to your usage)
  // When clicked, this will open a drawer with your block's fields
  // so your editors can edit them
  InlineBlockEditButton,
  BlockEditButton,

  // Buttons that will remove this block from Lexical
  // (choose the one that corresponds to your usage)
  InlineBlockRemoveButton,
  BlockRemoveButton,

  // The label that should be rendered for an inline block
  InlineBlockLabel,

  // The default "container" that is rendered for an inline block
  // if you want to re-use it
  InlineBlockContainer,

  // The default "collapsible" UI that is rendered for a regular block
  // if you want to re-use it
  BlockCollapsible,
} from '@payloadcms/richtext-lexical/client'

Copying and Pasting Blocks

The Admin Panel includes built-in copy and paste support for both individual block rows and entire Blocks fields. This is available through the row action menu (the ... button on each block) and from the field-level action menu in the field header.

Row-level vs. Field-level

  • Row copy/paste — copies a single block and lets you paste it into any position within any compatible Blocks field
  • Field copy/paste — copies all blocks in the field at once and pastes them as the full contents of a target field, replacing whatever was there

How it differs from Duplicate

The Duplicate action creates an immediate in-place copy of a block, inserted directly below the original — always within the same field on the same document.

Copy/paste is designed for moving data across fields or documents:

  • Copy a block on Page A, open Page B, and paste it into that page's blocks field
  • Copy a block from one Blocks field and paste it into a different Blocks field on the same document

How it works

Copied data is written to localStorage under the key _payloadClipboard. This means:

  • The clipboard persists across browser tabs (same origin)
  • It is not shared between different Payload origins

When pasting, Payload validates that the copied block type exists in the target field's blocks config. If the schemas are incompatible, the paste action will not be available. All block and nested array IDs are automatically regenerated on paste to prevent duplicate key errors.

<Banner type="warning"> **"Paste Fields" replaces all blocks, even when a single row is on the clipboard.**

If you have copied a single block row and then use Paste Fields (the field-level paste action in the field header), all existing blocks in the target field will be replaced with just that one copied row.

To add a copied row to a field that already has content, use Paste Row instead: add a new empty block first, then use the row-level Paste Row action on that new row to replace it with the copied data.

</Banner>

Blocks Items

Config Options

Blocks are defined as separate configs of their own.

<Banner type="success"> **Tip:** Best practice is to define each block config in its own file, and then import them into your Blocks field as necessary. This way each block config can be easily shared between fields. For instance, using the "layout builder" example, you might want to feature a few of the same blocks in a Post collection as well as a Page collection. Abstracting into their own files trivializes their reusability. </Banner>
OptionDescription
slug *Identifier for this block type. Will be saved on each block as the blockType property.
fields *Array of fields to be stored in this block.
labelsCustomize the block labels that appear in the Admin dashboard. Auto-generated from slug if not defined. Alternatively you can use admin.components.Label for greater control.
interfaceNameCreate a top level, reusable Typescript interface & GraphQL type.
graphQL.singularNameText to use for the GraphQL schema name. Auto-generated from slug if not defined. NOTE: this is set for deprecation, prefer interfaceName.
dbNameCustom table name for this block type when using SQL Database Adapter (Postgres). Auto-generated from slug if not defined.
customExtension point for adding custom data (e.g. for plugins)

* An asterisk denotes that a property is required.

Admin Options

Blocks are not fields, so they don’t inherit the base properties shared by all fields (not to be confused with the Blocks Field, documented above, which does). Here are their available admin options:

| Option | Description | | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --- | | components.Block | Custom component for replacing the Block, including the header. | | components.Label | Custom component for replacing the Block Label. | | disableBlockName | Hide the blockName field by setting this value to true. | | group | Text or localization object used to group this Block in the Blocks Drawer. | | custom | Extension point for adding custom data (e.g. for plugins) | | images | Custom images for the block in different UI contexts. Supports icon (20x20px for Lexical menus/toolbars) and thumbnail (3:2 ratio for block selection drawer). Each can be a URL string or { url, alt } object. More details. | |

Block Image Guidelines

The images property lets you provide custom images for each display context:

  • images.icon - Small icon for Lexical editor menus and toolbars (displayed at 20x20px)
  • images.thumbnail - Larger thumbnail for block selection drawer (3:2 aspect ratio)

Each can be either a plain URL string or an object { url: string, alt?: string }.

Icon (images.icon)

Used in Lexical editor slash menus, toolbar dropdowns, and inline block menus.

Requirements:

  • Displayed at 20x20 pixels
  • Square images (1:1 aspect ratio) work best
  • Falls back to images.thumbnail, then to default block icon

Recommendations:

  • Use SVG for crisp rendering at small sizes
  • Keep designs simple with bold shapes
  • Provide web-optimized images (SVG, PNG with transparency)

Thumbnail (images.thumbnail)

Used in the block selection drawer when editors add blocks to a blocks field.

Requirements:

  • 3:2 aspect ratio (e.g., 480x320, 600x400, 900x600)
  • Images are scaled using object-fit: cover
  • Non-matching aspect ratios will be cropped to fill the container

Recommendations:

  • Use images with 3:2 aspect ratio to avoid unwanted cropping
  • Keep important visual content centered in your image
  • Provide web-optimized images (JPEG, PNG, WebP) for faster loading

Usage Examples

Example 1: Using both icon and thumbnail with alt text

ts
const QuoteBlock: Block = {
  slug: 'quote',
  admin: {
    images: {
      icon: {
        url: 'https://example.com/icons/quote-icon-20x20.svg',
        alt: 'Quote icon',
      },
      thumbnail: {
        url: 'https://example.com/thumbnails/quote-block-480x320.jpg',
        alt: 'Quote block',
      },
    },
  },
  fields: [
    {
      name: 'quoteText',
      type: 'text',
      required: true,
    },
  ],
}

Example 2: Using URL strings (no alt text)

ts
const CallToActionBlock: Block = {
  slug: 'cta',
  admin: {
    images: {
      icon: 'https://example.com/icons/cta-20x20.svg',
      thumbnail: 'https://example.com/thumbnails/cta-block-480x320.jpg',
    },
  },
  fields: [
    {
      name: 'buttonText',
      type: 'text',
    },
  ],
}

Example 3: Using only icon

ts
const DividerBlock: Block = {
  slug: 'divider',
  admin: {
    images: {
      icon: 'https://example.com/icons/divider-20x20.svg',
    },
  },
  fields: [],
}

If no images is provided, default graphics are displayed automatically in both contexts.

blockType, blockName, and block.label

Each block stores two pieces of data alongside your fields. The blockType identifies which schema to use and it is exactly the block’s slug. The blockName is an optional label you can give to a block to make editing and scanning easier.

The label is shared by all blocks of the same type and is defined in the block config via label with a fallback to slug. On the other hand, the blockName is specific to each block individually. You can hide the editable name with admin.disableBlockName.

If you provide admin.components.Label, that component replaces both the name and the label in the Admin UI.

PropertyScopeSourceVisible in UINotes
blockTypeEach blockThe block’s slugNot a headerUsed to resolve which block schema to render
blockNameEach blockEditor input in the AdminYesOptional label; hide with admin.disableBlockName or replace with custom admin.components.Label
block.labelBlock typelabel in block config or slug fallbackYesShared by all blocks of that type. Can be replaced with custom admin.components.Label

Custom Components

Field

Server Component
tsx
import type React from 'react'
import { BlocksField } from '@payloadcms/ui'
import type { BlocksFieldServerComponent } from 'payload'

export const CustomBlocksFieldServer: BlocksFieldServerComponent = ({
  clientField,
  path,
  schemaPath,
  permissions,
}) => {
  return (
    <BlocksField
      field={clientField}
      path={path}
      schemaPath={schemaPath}
      permissions={permissions}
    />
  )
}
Client Component
tsx
'use client'
import React from 'react'
import { BlocksField } from '@payloadcms/ui'
import type { BlocksFieldClientComponent } from 'payload'

export const CustomBlocksFieldClient: BlocksFieldClientComponent = (props) => {
  return <BlocksField {...props} />
}

Label

Server Component
tsx
import React from 'react'
import { FieldLabel } from '@payloadcms/ui'
import type { BlocksFieldLabelServerComponent } from 'payload'

export const CustomBlocksFieldLabelServer: BlocksFieldLabelServerComponent = ({
  clientField,
  path,
}) => {
  return (
    <FieldLabel
      label={clientField?.label || clientField?.name}
      path={path}
      required={clientField?.required}
    />
  )
}
Client Component
tsx
'use client'
import React from 'react'
import { FieldLabel } from '@payloadcms/ui'
import type { BlocksFieldLabelClientComponent } from 'payload'

export const CustomBlocksFieldLabelClient: BlocksFieldLabelClientComponent = ({
  label,
  path,
  required,
}) => {
  return (
    <FieldLabel
      label={field?.label || field?.name}
      path={path}
      required={field?.required}
    />
  )
}

Example

collections/ExampleCollection.js

ts
import { Block, CollectionConfig } from 'payload'

const QuoteBlock: Block = {
  slug: 'Quote', // required
  imageURL: 'https://google.com/path/to/image.jpg',
  imageAltText: 'A nice thumbnail image to show what this block looks like',
  interfaceName: 'QuoteBlock', // optional
  fields: [
    // required
    {
      name: 'quoteHeader',
      type: 'text',
      required: true,
    },
    {
      name: 'quoteText',
      type: 'text',
    },
  ],
}

export const ExampleCollection: CollectionConfig = {
  slug: 'example-collection',
  fields: [
    {
      name: 'layout', // required
      type: 'blocks', // required
      minRows: 1,
      maxRows: 20,
      blocks: [
        // required
        QuoteBlock,
      ],
    },
  ],
}

Block References

If you have multiple blocks used in multiple places, your Payload Config can grow in size, potentially sending more data to the client and requiring more processing on the server. However, you can optimize performance by defining each block once in your Payload Config and then referencing its slug wherever it's used instead of passing the entire block config.

To do this, define the block in the blocks array of the Payload Config. Then, in the Blocks Field, pass the block slug to the blockReferences array - leaving the blocks array empty for compatibility reasons.

ts
import { buildConfig } from 'payload'
import { lexicalEditor, BlocksFeature } from '@payloadcms/richtext-lexical'

// Payload Config
const config = buildConfig({
  // Define the block once
  blocks: [
    {
      slug: 'TextBlock',
      fields: [
        {
          name: 'text',
          type: 'text',
        },
      ],
    },
  ],
  collections: [
    {
      slug: 'collection1',
      fields: [
        {
          name: 'content',
          type: 'blocks',
          // Reference the block by slug
          blockReferences: ['TextBlock'],
          blocks: [], // Required to be empty, for compatibility reasons
        },
      ],
    },
    {
      slug: 'collection2',
      fields: [
        {
          name: 'editor',
          type: 'richText',
          editor: lexicalEditor({
            features: [
              BlocksFeature({
                // Same reference can be reused anywhere, even in the lexical editor, without incurred performance hit
                blocks: ['TextBlock'],
              }),
            ],
          }),
        },
      ],
    },
  ],
})
<Banner type="warning"> **Reminder:** Blocks referenced in the `blockReferences` array are treated as isolated from the collection / global config. This has the following implications:
  1. The block config cannot be modified or extended in the collection config. It will be identical everywhere it's referenced.
  2. Access control for blocks referenced in the blockReferences are run only once - data from the collection will not be available in the block's access control. </Banner>

TypeScript

As you build your own Block configs, you might want to store them in separate files but retain typing accordingly. To do so, you can import and use Payload's Block type:

ts
import type { Block } from 'payload'

Conditional Blocks

Blocks can be conditionally enabled using the filterOptions property on the blocks field. It allows you to provide a function that returns which block slugs should be available based on the given context.

Behavior

  • filterOptions is re-evaluated as part of the form state request, whenever the document data changes.
  • If a block is present in the field but no longer allowed by filterOptions, a validation error will occur when saving.

filterOptions Example

ts
{
  name: 'blocksWithDynamicFilterOptions',
  type: 'blocks',
  filterOptions: ({ siblingData }) => {
    return siblingData?.enabledBlocks?.length
      ? [siblingData.enabledBlocks] // allow only the matching block
      : true // allow all blocks if no value is set
  },
  blocks: [
    { slug: 'block1', fields: [{ type: 'text', name: 'block1Text' }] },
    { slug: 'block2', fields: [{ type: 'text', name: 'block2Text' }] },
    { slug: 'block3', fields: [{ type: 'text', name: 'block3Text' }] },
    // ...
  ],
}

In this example, the list of available blocks is determined by the enabledBlocks sibling field. If no value is set, all blocks remain available.