How to useBlockProps()

11.9k views Asked by At

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

There are 3 answers

0
Numenx On

I had the same problem extending the columns Block. Seems like this function isnt implemented in the Wordpress 5.5 core. You can try installing the gutenberg plugin to get the latest version of Gutenberg or use the template from the wp5.5 branch. https://github.com/WordPress/gutenberg/blob/wp/5.5/packages/block-library/src/button/edit.js

0
PattyOK On

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

0
Albin On

useBlockProps is available in 5.6 as you can read here https://developer.wordpress.org/block-editor/developers/block-api/versions/ you can find it wp.blockEditor.useBlockProps

Let me know if you find how to change the wrapping element (not the classes). Thanks.