0

I'm trying to implement a bootstrap5 carousel component as a Gutenberg block. It all appears to be working as intended, except for adding the "active" class to a first element.

I tried to find siblings of the current inner block by using getBlockParents and getBlocksByClientId Here is the JS code:

    const select = window.wp.data.select('core/block-editor');

    blocks.registerBlockType('natural/bootstrap5-carousel-item', {
        apiVersion: 2,
        title: __('Carousel Item'),
        icon: 'format-gallery',
        category: 'design',
        parent: ['natural/bootstrap5-carousel'],
        example: {},
        edit: function () {
            return el(
                'div',
                useBlockProps({
                    style: {
                        padding: '20px',
                        border: '2px solid #000'
                    }
                }),
                el( InnerBlocks )
            )
        },
        save: function (props) {
            const parentBlocks = select.getBlockParents(props.clientId); // empty in save method, works in console
            const directParent = select.getBlocksByClientId(parentBlocks[parentBlocks.length - 1])[0];
            const siblings = directParent.innerBlocks;

            let classNameSuffix = '';
            if (siblings[0].attributes.clientId === props.clientId) {
                classNameSuffix = ' active';
            }

            return el(
                'div',
                useBlockProps.save({
                    className: 'carousel-item' + classNameSuffix
                }),
                el( InnerBlocks.Content )
            )
        },
    });

Unfortunately, the method I tried returns an error because parentBlocks is empty. Any idea why? The code works in the web console, but appears to be breaking in the save method.

0

1 Answer 1

1

A save component is intended to save static HTML, and can rely only on the blocks attribute. No interactivity, no local state, no AJAX requests, etc, just block attributes.

If you achieve what you're trying to do you'll immediately run into a new problem with block validation failure. You cannot use the save component to figure out this information. Figure it out somewhere else and store it as an attribute, ideally in the edit component.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.