In a Gutenberg block I try to read the value of an attribute's default property, so that I can find out in the transformation routine (to another block type) if any give attribute still has the default value.

With this.props.attributes I only see the values of attributes, but I need their "meta data".

One sample declaration in registerBlockType would look like:

attributes: {
    amount: {
      type: 'integer',
      default: 1
    },
// ...
}

I'm not sure if there's a direct way to inspect an attributes default value but one way would you can indirectly achieve this is to store the default value in a variable.

You could then reference it from inside the attribute object and from the edit and save functions.

e.g. (untested)

const amountDefault = 1;

registerBlockType( 'test/myblock', {
    title: __( 'Test Block' ),
    attributes: {
        amount: {
            type: 'integer',
            default: amountDefault 
        }
    },
    edit: function( props ) {
        const { attributes: { amount } } = props;

        return (
            <div className={ props.className }>
                <h3>Editor</h3>
                The default amount is: {amountDefault}
                The actual amount is: {amount}
            </div>
        );
    },
    save: function( props ) {
        const { attributes: { amount } } = props;
        return (
            <div>
                <h3>Editor</h3>
                The default amount is: {amountDefault}
                The actual amount is: {amount}
            </div>
        );
    }
} );

This isn't ideal but should work as expected.

  • That sounds like a good solution, as there doesn't seem to be a way how to access it directly. – chris_cm May 21 at 10:40
up vote 0 down vote accepted

I just found out that I can simply define a variable when I register the block

var myBlock = registerBlockType( ... )

and then inside the anonymous function for "transform" I can access the attributes as

myBlock.attributes

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.