Build a Block Series – Part 4: Block Attributes

The third part in my series walking through building a Gutenberg block for the WordPress editor. This lesson covers the anatomy of a block.

Previous casts:

Block Attributes

Attributes are the way a block stores data, they define how a block is parsed to extract data from the saved content.

See the Block Attributes documentation for details and examples.

The following code defines a url attribute of type string, and the source is the text part of a tag with the className theurl.

attributes: {
    url: {
        type: 'string',
        source: 'text',
        selector: '.theurl',
    },
},

Edit and Save

The edit and save functions are passed the attributes and setAttributes parameters. These were omitted because we didn’t use them in Part 3. The attributes is a JavaScript object containing the values of each attribute, or default values if defined. The setAttributes parameter is a function to update an attribute. If you are familiar with React, this is similar to state and setState.

TextControl Component

The component we are going to use is the TextControl component, it is similar to an HTML text input field. You can see documentation for TextControl component and a complete list of components in the handbook. You can also browse an interactive set of components in this Storybook, it is still in development, so not a complete set of components.

The component is added similar to an HTML tag, setting a label, the value is set to the attributes.url and the onChange function uses the setAttributes to update the url attribute value.

The save function will simply write the attributes.url as a div tag with the className set to theurl so it can be parsed.

Here is the updated edit and save functions using the attributes and TextControl component.


edit: ( { attributes, setAttributes } ) => {
    return (
        <div>
            <TextControl
                label="URL"
                value={ attributes.url }
                onChange={ ( val ) => setAttributes( { url: val } ) }
            />
        </div>
    );
},
save: ( { attributes } ) => {
    return (
        <div className="theurl">{ attributes.url }</div>
    );
}

Code for this part at: https://github.com/mkaz/qrcode-block/tree/part-4