@daniloparrajr

Using the useBlockProps React hook in Block API version 2 or higher

  • 8/20/2023
  • 1 min read

You must use this hook in your block’s edit and save function to insert the attributes and event handlers needed to enable block behaviour. Any attributes you wish to pass to the block element must be passed through useBlockProps and the returned value be spread onto the element.

edit.js
import { useBlockProps } from "@wordpress/block-editor";
function Edit({ attributes }) {
const blockProps = useBlockProps({
style: { "--drop-cap-color": attributes.dropCapColor },
});
return <p {...blockProps}>{attributes.content}</p>;
}

Use the save() function of useBlockProps hook in your block’s save function to save your custom attributes.

save.js
import { useBlockProps } from "@wordpress/block-editor";
export default function save({ attributes }) {
const blockProps = useBlockProps.save({
style: { "--drop-cap-color": attributes.dropCapColor },
});
return <p {...blockProps}>{attributes.content}</p>;
}

Make sure you are using Block API version 2 or higher in your block.json.

block.json
{
"$schema": "https://schemas.wp.org/trunk/block.json",
"apiVersion": 3,
"name": "create-block/multi-columns",
"title": "Multi Columns",
"version": "0.1.0",
...
}

All of this will be automatically done for you if you use the @wordpress/create-block scaffolding tool of WordPress.

References

Block API Versions

Block API version 2 dev note

Related Articles