Components - useBlockProps
By default, Gutenberg has to create a wrapper around blocks to make them interactive inside the editor. This can become problematic for some block types like containers or columns, since the markup between editor and frontend will be different. The useBlockProps hook makes it possible to mark an element inside the block template as the root element, thus creating markup parity between editor and frontend.
Usage
Simply add the useBlockProps
attribute to the root element of your block.
<div useBlockProps class="my-class"> <!-- This element will be rendered as the root element of your block in Gutenberg. --> </div>
Copy
Blockstudio will automatically combine classes and attributes from the editor (alignment classes etc.) along with whatever is defined in the block templates. get_block_wrapper_attributes is being used under the hood for that.
<div class="my-class wp-block-your-black-name alignright"> </div>
Copy
Considerations
Root element
Since there can only be one root element in a block template, when using
useBlockProps
, the block template has to have a single root element. For
example, the following will not work and Gutenberg will create a wrapper around
the template.
<div useBlockProps> First root element. </div> <span> Second root element. </span>
Copy
Similarly, useBlockProps can only be used once per block template.
@ sign
Blockstudio converts the block template to valid React code inside Gutenberg
using html-react-parser. This
comes with the limitation that the @
character can't be used inside an HTML
attribute name.
Libraries like Alpine.js use the @
characters to define directives on HTML elements.
<button useBlockProps @click="console.log('hi')"> Click me </button>
Copy
Inside Gutenberg, this @click
attribute will be stripped from the element. (it
will still work on the frontend, of course)
To combat this issue, you can use the alternative syntax Alpine.js provides.
<button useBlockProps x-on:click="console.log('hi')"> Click me </button>
Copy
The above will work inside Gutenberg and on the frontend.