How to access “default” property of attribute in Gutenberg

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.

Leave a Comment