Frizzant
Frizzant

Reputation: 768

Adding innerBlock with attributes on click in Wordpress Gutenberg Editor

I am creating a gutenberg block with innerblocks. In this case the native core/cover block. I then add three innerblocks with the TEMPLATE variable, and load it in to <InnerBlocks ...>

My issue is, that when you add another cover block via editor, it does not have the innerBlockPresets which i defined. As far as I can tell allowedBlocks doesn't allow attributes.

I have to use the native cover block for this. How can I solve this?

edit.js

import {useBlockProps, InnerBlocks} from '@wordpress/block-editor';

export default function Edit(}) {

    const blockProps = useBlockProps();
    const ALLOWED_BLOCKS = ['core/cover'];
    const innerBlockPresets = {'className': 'is-awesome', 'align': 'full'};
    const TEMPLATE = [['core/cover', innerBlockPresets], ['core/cover', innerBlockPresets], ['core/cover', innerBlockPresets]];

    return (
        <div {...blockProps}>
                <InnerBlocks
                    allowedBlocks={ALLOWED_BLOCKS}
                    template={TEMPLATE}
                    renderAppender={() => <InnerBlocks.ButtonBlockAppender/>}
                />
        </div>
    );
}

Upvotes: 1

Views: 2357

Answers (1)

S.Walsh
S.Walsh

Reputation: 3699

A possible solution could be to register a block variation of core/cover, eg:

index.js

wp.blocks.registerBlockVariation('core/cover', {
    name: 'cover-variation',
    title: 'Cover Variation',
    icon: 'star-filled',
    attributes: {
        className: 'is-awesome',
        align: 'full'
    }
});

This enables you to have a predefined set of attributes. Next, if ALLOWED_BLOCKS in InnerBlocks contains core/cover, only core/cover & your cover-variation (or any other variations of cover) can be added, eg:

edit.js

import { __ } from '@wordpress/i18n';
import { useBlockProps, InnerBlocks } from '@wordpress/block-editor';

export default function Edit() {
    const ALLOWED_BLOCKS = ['core/cover'];
    const TEMPLATE = [
        ['core/cover', {
            className: 'is-awesome',
            align: 'full'
        }]];

    return (
        <div {...useBlockProps()}>
            <InnerBlocks
                allowedBlocks={ALLOWED_BLOCKS}
                template={TEMPLATE}
            />
        </div>
    );
}

enter image description here

An issue I've found with this approach is the variation cannot be set in TEMPLATE, as the block variation is registered after the core block but too late for InnerBlock template validation. If you try this, the InnerBlock template validation returns "undefined" when using a block variation and won't render. So to avoid this issue, in the TEMPLATE, set the same properties as your variation.

Upvotes: 2

Related Questions