Forum Replies Created

Viewing 1 replies (of 1 total)
  • That’s a great question. It’s one of the slightly confusing parts of the transforms API.

    The short answer is: with the structure you’re using, you don’t know which one the user picked. When you put multiple blocks inside a single transform object’s blocks array, you’re essentially telling Gutenberg that this one transform function is generic enough to handle all of them, which isn’t what you want here.

    To run different logic for each target block, you need to provide a separate transform object for each block inside the to array.

    Here is how you should structure your code:

    JavaScript

    registerBlockType( 'my/block', {
        title: 'My Block',
        category: 'widgets',
        attributes: {
            content: { type: 'string' },
        },
    
        transforms: {
            to: [
                {
                    type: 'block',
                    blocks: [ 'core/paragraph' ], // Only paragraph here
                    transform: ( attributes ) => {
                        // This logic only runs when transforming TO a Paragraph
                        return createBlock( 'core/paragraph', {
                            content: attributes.content,
                        } );
                    },
                },
                {
                    type: 'block',
                    blocks: [ 'core/heading' ], // Only heading here
                    transform: ( attributes ) => {
                        // This logic only runs when transforming TO a Heading
                        return createBlock( 'core/heading', {
                            content: attributes.content,
                            // You could add other default attributes here
                            // level: 2, 
                        } );
                    },
                },
            ],
        },
    } );
Viewing 1 replies (of 1 total)