Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

How to implement Recursive Block?

default discord avatar
GeorgeHulpoilast year
1 1

Hello! I want to implement a recursive block.

export const HTMLElementBlock: Block = {
	slug: 'html-element',
	labels: {
		singular: 'HTML Element Block',
		plural: 'HTML Element Blocks',
	},
	interfaceName: 'HTMLElementBlock',
	fields: [
		{
			name: 'layout',
			type: 'blocks',
			blocks: [
				HTMLElementBlock,
				// rest of blocks
			],
		},
	],
};

The only problem is that I can't use the HTMLElementBlock before its declaration. How I am supposed to create a Recursive Block?

  • Selected Answer
    default discord avatar
    GeorgeHulpoilast year

    I managed to resolve the issue with this code:

    import { Block, Field } from 'payload/types';
    
    type HTMLElementBlockType = (options?: {
    	depth?: number;
    }) => Block;
    
    const block: HTMLElementBlockType = ({ depth = 0 } = {}) => {
    	const layoutField: Field = {
    		name: 'layout',
    		type: 'blocks',
    		blocks: [],
    	};
    
    	let o = {
    		slug: 'html-element',
    		labels: {
    			singular: 'HTML Element Block',
    			plural: 'HTML Element Blocks',
    		},
    		interfaceName: 'HTMLElementBlock',
    		fields: [layoutField],
    	};
    
    	if (depth < 5) {
    		layoutField.blocks.push(block({ depth: depth + 1 }));
    	}
    
    	return o;
    };
    
    export default block;
Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.