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.