How to useBlockProps()

Viewed 7696

I'm trying to rebuild and extend the original Wordpress blocks for Buttons & Button.

I created the boilerplate with npx @wordpress/create-block, copied the original code,...

It works as long as I remove the useBlockProps() part. e.g. here (original file)

[...]

    const colorProps = getColorAndStyleProps( attributes, colors, true );
    const blockProps = useBlockProps();

    return (
        <>
            <ColorEdit { ...props } />
            <div { ...blockProps }>
                <RichText
[...]

If I use it, I get Uncaught TypeError: Object(...) is not a function in the console.

3 Answers

In order to use BlockProps you need to set the apiVersion to 2 in the block settings when you register the block.

registerBlockType("my-blocks/my-custom-block", {
    apiVersion: 2,
    title: __("My Custom Block", "my-blocks"),
    attributes: ...
});

A little more info here: https://developer.wordpress.org/block-editor/developers/block-api/block-edit-save/

Though what's not mentioned there, if you are currently using Class Architecture to build and export components, you will need to migrate that into a pure function architecture (you know this is the case when you get the dreaded Invalid Hook Call).

Related