'Floating blocks in Gutenberg editor
I am trying to develop a block that can align left/right in a floating way like do the blocks core/image, core/audio, ... I mean that the UI of Gutenberg adapts to that position and you can have a paragraph arround the aligned/floating block. All of it very natural/native.
I have been contrasting the HTML generated by their blocks and the source code.
In the first example, there is a paragraph with class wp-block among others. That's the normal composition. The most external element of your block gets all the Gutenberg classes.
In the second example, there is a div with only the class wp-block and the data-align attribute. That's the behaviuor that I am tring to replicate.
HTML structure created by the core/audio block:
How is shown the core/audio block:
Here is my code and the problem visually explained.
The code is very similar to https://github.com/WordPress/gutenberg/blob/master/packages/block-library/src/audio/edit.js
const { useBlockProps } = wp.blockEditor;
const { BlockAlignmentToolbar, BlockControls } = wp.editor;
const { Component } = wp.element;
wp.blocks.registerBlockType( 'melange/test-aligns', {
category: 'melangeLayout',
title: 'Test aligns',
description: '',
attributes: {
align: { type: 'string', default: null, },
},
// supports: { align: true },
edit: function({attributes, setAttributes}) {
const blockProps = useBlockProps();
return <>
<BlockControls>
<BlockAlignmentToolbar
value = { attributes.align }
onChange = { align => setAttributes({align}) }
/>
</BlockControls>
<p {...blockProps}>Hello world!</p>
</>
},
getEditWrapperProps(attrs) {
return { ...attrs, 'data-align': attrs.align };
},
save: function() {
const blockProps = useBlockProps.save();
return <p {...blockProps}>Hello world!</p>;
},
});
My problem is that the floating block has two blockcontrols depending where is the mouse hovering.
And the reason is the created divs doesn´t have the same structure as they have in core blocks. I don´t know why, my block gets wrapped by an extra div which is not needed, in fact duplicates the id.
Solution 1:[1]
Solution:
wp.blocks.registerBlockType( 'melange/test-aligns', {
apiVersion: 2,
...
});
As seen in https://developer.wordpress.org/block-editor/developers/block-api/block-edit-save/
But, I don´t know why, they don´t need it in Gutenberg source code.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Albin |