Creating Reusable Blocks in Payload CMS

Reusable blocks are one of the most powerful features in Payload CMS, enabling developers to define modular content components that can be reused across various pages and collections. This approach streamlines content management, promotes consistency, and simplifies maintenance.

What Are Reusable Blocks?

In Payload CMS, a block is a group of fields bundled together to represent a specific type of content, such as a hero section, a call-to-action (CTA), or a testimonial. Reusable blocks allow you to define these content components once and use them in multiple places.

Defining Reusable Blocks

In the collection where you want to use blocks, add a blocks field of type array. Inside this field, define the block types and their associated fields.

import { buildConfig } from 'payload/config';

const BlockTypes = {
  HERO: 'hero',
  CTA: 'cta',
};

const Collections = [
  {
    slug: 'pages',
    fields: [
      {
        name: 'blocks',
        type: 'array',
        label: 'Page Blocks',
        minRows: 1,
        blocks: [
          {
            slug: BlockTypes.HERO,
            fields: [
              {
                name: 'title',
                type: 'text',
                label: 'Hero Title',
                required: true,
              },
            ],
          },
          {
            slug: BlockTypes.CTA,
            fields: [
              {
                name: 'text',
                type: 'text',
                label: 'CTA Text',
                required: true,
              },
            ],
          },
        ],
      },
    ],
  },
];

export default buildConfig({
  collections: Collections,
});

Using Reusable Blocks

Add Blocks to a Page

  • In the admin panel, navigate to your collection (e.g., Pages) and add blocks. You’ll see options for each block type (Hero, CTA). Fill out the fields for each block.

Render Blocks in the Frontend

  • Fetch the blocks field from the API and render the blocks dynamically in your frontend code

import React from 'react';

const BlockRenderer = ({ blocks }) => {
  return blocks.map((block, index) => {
    switch (block.blockType) {
      case 'hero':
        return <Hero key={index} {...block} />;
      case 'cta':
        return <CTA key={index} {...block} />;
      default:
        return null;
    }
  });
};

export default BlockRenderer;

Conclusion

Reusable blocks in Payload CMS empower developers and content editors to collaborate more effectively, creating a modular and scalable system for content management. Start building reusable blocks today to unlock the full potential of your Payload CMS projects!

Leave a comment

Your email address will not be published. Required fields are marked *