Components - useBlockProps

Last modified:

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.

index.php

                <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.

index.php

                <div class="my-class wp-block-your-black-name alignright">
    </div>
Copy

Considerations

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:

index.php

                <div useBlockProps>
      First root element.
    </div>
    <span>
      Second root element.
    </span>
Copy

Similarly, useBlockProps can only be used once per block template.

Search